Search in sources :

Example 16 with SslHandler

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslHandler in project pravega by pravega.

the class ConnectionFactoryImplTest method setUp.

@Before
public void setUp() throws Exception {
    // Configure SSL.
    port = TestUtils.getAvailableListenPort();
    final SslContext sslCtx;
    if (ssl) {
        try {
            sslCtx = SslContextBuilder.forServer(new File("../config/cert.pem"), new File("../config/key.pem")).build();
        } catch (SSLException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslCtx = null;
    }
    boolean nio = false;
    EventLoopGroup bossGroup;
    EventLoopGroup workerGroup;
    try {
        bossGroup = new EpollEventLoopGroup(1);
        workerGroup = new EpollEventLoopGroup();
    } catch (ExceptionInInitializerError | UnsatisfiedLinkError | NoClassDefFoundError e) {
        nio = true;
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
    }
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(nio ? NioServerSocketChannel.class : EpollServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            if (sslCtx != null) {
                SslHandler handler = sslCtx.newHandler(ch.alloc());
                SSLEngine sslEngine = handler.engine();
                SSLParameters sslParameters = sslEngine.getSSLParameters();
                sslParameters.setEndpointIdentificationAlgorithm("LDAPS");
                sslEngine.setSSLParameters(sslParameters);
                p.addLast(handler);
            }
        }
    });
    // Start the server.
    serverChannel = b.bind("localhost", port).awaitUninterruptibly().channel();
}
Also used : EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) LoggingHandler(io.netty.handler.logging.LoggingHandler) SSLEngine(javax.net.ssl.SSLEngine) SSLException(javax.net.ssl.SSLException) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) SSLException(javax.net.ssl.SSLException) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SSLParameters(javax.net.ssl.SSLParameters) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) File(java.io.File) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext) Before(org.junit.Before)

Example 17 with SslHandler

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslHandler in project reactor-netty by reactor.

the class ContextHandler method addSslAndLogHandlers.

static void addSslAndLogHandlers(NettyOptions<?, ?> options, ContextHandler<?> sink, LoggingHandler loggingHandler, boolean secure, Tuple2<String, Integer> sniInfo, ChannelPipeline pipeline) {
    SslHandler sslHandler = secure ? options.getSslHandler(pipeline.channel().alloc(), sniInfo) : null;
    if (sslHandler != null) {
        if (log.isDebugEnabled() && sniInfo != null) {
            log.debug("SSL enabled using engine {} and SNI {}", sslHandler.engine().getClass().getSimpleName(), sniInfo);
        } else if (log.isDebugEnabled()) {
            log.debug("SSL enabled using engine {}", sslHandler.engine().getClass().getSimpleName());
        }
        if (log.isTraceEnabled()) {
            pipeline.addFirst(NettyPipeline.SslLoggingHandler, new LoggingHandler(SslReadHandler.class));
            pipeline.addAfter(NettyPipeline.SslLoggingHandler, NettyPipeline.SslHandler, sslHandler);
        } else {
            pipeline.addFirst(NettyPipeline.SslHandler, sslHandler);
        }
        if (log.isDebugEnabled()) {
            pipeline.addAfter(NettyPipeline.SslHandler, NettyPipeline.LoggingHandler, loggingHandler);
            pipeline.addAfter(NettyPipeline.LoggingHandler, NettyPipeline.SslReader, new SslReadHandler(sink));
        } else {
            pipeline.addAfter(NettyPipeline.SslHandler, NettyPipeline.SslReader, new SslReadHandler(sink));
        }
    } else if (log.isDebugEnabled()) {
        pipeline.addFirst(NettyPipeline.LoggingHandler, loggingHandler);
    }
}
Also used : LoggingHandler(io.netty.handler.logging.LoggingHandler) SslHandler(io.netty.handler.ssl.SslHandler)

Example 18 with SslHandler

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslHandler in project component-runtime by Talend.

the class PassthroughHandler method channelRead0.

@Override
protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) {
    if (HttpMethod.CONNECT.name().equalsIgnoreCase(request.method().name())) {
        final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.EMPTY_BUFFER);
        setKeepAlive(response, true);
        setContentLength(response, 0);
        if (api.getSslContext() != null) {
            final SSLEngine sslEngine = api.getSslContext().createSSLEngine();
            sslEngine.setUseClientMode(false);
            ctx.channel().pipeline().addFirst("ssl", new SslHandler(sslEngine, true));
            final String uri = request.uri();
            final String[] parts = uri.split(":");
            ctx.channel().attr(BASE).set("https://" + parts[0] + (parts.length > 1 && !"443".equals(parts[1]) ? ":" + parts[1] : ""));
        }
        ctx.writeAndFlush(response);
        return;
    }
    // copy to use in a separated thread
    final FullHttpRequest req = request.copy();
    api.getExecutor().execute(() -> doHttpRequest(req, ctx));
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) SSLEngine(javax.net.ssl.SSLEngine) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) SslHandler(io.netty.handler.ssl.SslHandler)

Example 19 with SslHandler

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslHandler in project component-runtime by Talend.

the class ServingProxyHandler method channelRead0.

@Override
protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) {
    if (!request.decoderResult().isSuccess()) {
        sendError(ctx, HttpResponseStatus.BAD_REQUEST);
        return;
    }
    api.getExecutor().execute(() -> {
        final Map<String, String> headers = StreamSupport.stream(Spliterators.spliteratorUnknownSize(request.headers().iteratorAsString(), Spliterator.IMMUTABLE), false).collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
        final Attribute<String> baseAttr = ctx.channel().attr(Handlers.BASE);
        Optional<Response> matching = api.getResponseLocator().findMatching(new RequestImpl((baseAttr == null || baseAttr.get() == null ? "" : baseAttr.get()) + request.uri(), request.method().name(), headers), api.getHeaderFilter());
        if (!matching.isPresent()) {
            if (HttpMethod.CONNECT.name().equalsIgnoreCase(request.method().name())) {
                final Map<String, String> responseHeaders = new HashMap<>();
                responseHeaders.put(HttpHeaderNames.CONNECTION.toString(), HttpHeaderValues.KEEP_ALIVE.toString());
                responseHeaders.put(HttpHeaderNames.CONTENT_LENGTH.toString(), "0");
                matching = of(new ResponseImpl(responseHeaders, HttpResponseStatus.OK.code(), Unpooled.EMPTY_BUFFER.array()));
                if (api.getSslContext() != null) {
                    final SSLEngine sslEngine = api.getSslContext().createSSLEngine();
                    sslEngine.setUseClientMode(false);
                    ctx.channel().pipeline().addFirst("ssl", new SslHandler(sslEngine, true));
                    final String uri = request.uri();
                    final String[] parts = uri.split(":");
                    ctx.channel().attr(Handlers.BASE).set("https://" + parts[0] + (parts.length > 1 && !"443".equals(parts[1]) ? ":" + parts[1] : ""));
                }
            } else {
                sendError(ctx, new HttpResponseStatus(HttpURLConnection.HTTP_BAD_REQUEST, "You are in proxy mode. No response was found for the simulated request. Please ensure to capture it for next executions. " + request.method().name() + " " + request.uri()));
                return;
            }
        }
        final Response resp = matching.get();
        final ByteBuf bytes = ofNullable(resp.payload()).map(Unpooled::copiedBuffer).orElse(Unpooled.EMPTY_BUFFER);
        final HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(resp.status()), bytes);
        HttpUtil.setContentLength(response, bytes.array().length);
        if (!api.isSkipProxyHeaders()) {
            response.headers().set("X-Talend-Proxy-JUnit", "true");
        }
        ofNullable(resp.headers()).ifPresent(h -> h.forEach((k, v) -> response.headers().set(k, v)));
        ctx.writeAndFlush(response);
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) HttpVersion(io.netty.handler.codec.http.HttpVersion) Handlers.sendError(org.talend.sdk.component.junit.http.internal.impl.Handlers.sendError) Handlers.closeOnFlush(org.talend.sdk.component.junit.http.internal.impl.Handlers.closeOnFlush) Spliterators(java.util.Spliterators) Optional.of(java.util.Optional.of) Response(org.talend.sdk.component.junit.http.api.Response) HashMap(java.util.HashMap) SSLEngine(javax.net.ssl.SSLEngine) HttpApiHandler(org.talend.sdk.component.junit.http.api.HttpApiHandler) Unpooled(io.netty.buffer.Unpooled) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Collectors.toMap(java.util.stream.Collectors.toMap) ByteBuf(io.netty.buffer.ByteBuf) Map(java.util.Map) StreamSupport(java.util.stream.StreamSupport) Attribute(io.netty.util.Attribute) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) Optional.ofNullable(java.util.Optional.ofNullable) HttpMethod(io.netty.handler.codec.http.HttpMethod) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) Slf4j(lombok.extern.slf4j.Slf4j) SslHandler(io.netty.handler.ssl.SslHandler) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) Optional(java.util.Optional) ChannelHandler(io.netty.channel.ChannelHandler) HttpResponse(io.netty.handler.codec.http.HttpResponse) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) AllArgsConstructor(lombok.AllArgsConstructor) Spliterator(java.util.Spliterator) HttpUtil(io.netty.handler.codec.http.HttpUtil) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HashMap(java.util.HashMap) SSLEngine(javax.net.ssl.SSLEngine) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) ByteBuf(io.netty.buffer.ByteBuf) SslHandler(io.netty.handler.ssl.SslHandler) Response(org.talend.sdk.component.junit.http.api.Response) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) HashMap(java.util.HashMap) Collectors.toMap(java.util.stream.Collectors.toMap) Map(java.util.Map)

Example 20 with SslHandler

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslHandler in project redisson by redisson.

the class RedisChannelInitializer method initSsl.

private void initSsl(final RedisClientConfig config, Channel ch) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, SSLException, UnrecoverableKeyException {
    if (!config.getAddress().isSsl()) {
        return;
    }
    io.netty.handler.ssl.SslProvider provided = io.netty.handler.ssl.SslProvider.JDK;
    if (config.getSslProvider() == SslProvider.OPENSSL) {
        provided = io.netty.handler.ssl.SslProvider.OPENSSL;
    }
    SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().sslProvider(provided);
    sslContextBuilder.protocols(config.getSslProtocols());
    if (config.getSslTruststore() != null) {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream stream = config.getSslTruststore().openStream();
        try {
            char[] password = null;
            if (config.getSslTruststorePassword() != null) {
                password = config.getSslTruststorePassword().toCharArray();
            }
            keyStore.load(stream, password);
        } finally {
            stream.close();
        }
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        sslContextBuilder.trustManager(trustManagerFactory);
    }
    if (config.getSslKeystore() != null) {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream stream = config.getSslKeystore().openStream();
        char[] password = null;
        if (config.getSslKeystorePassword() != null) {
            password = config.getSslKeystorePassword().toCharArray();
        }
        try {
            keyStore.load(stream, password);
        } finally {
            stream.close();
        }
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);
        sslContextBuilder.keyManager(keyManagerFactory);
    }
    SSLParameters sslParams = new SSLParameters();
    if (config.isSslEnableEndpointIdentification()) {
        sslParams.setEndpointIdentificationAlgorithm("HTTPS");
    } else {
        if (config.getSslTruststore() == null) {
            sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
        }
    }
    SslContext sslContext = sslContextBuilder.build();
    String hostname = config.getSslHostname();
    if (hostname == null || NetUtil.createByteArrayFromIpAddressString(hostname) != null) {
        hostname = config.getAddress().getHost();
    }
    SSLEngine sslEngine = sslContext.newEngine(ch.alloc(), hostname, config.getAddress().getPort());
    sslEngine.setSSLParameters(sslParams);
    SslHandler sslHandler = new SslHandler(sslEngine);
    ch.pipeline().addLast(sslHandler);
    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

        volatile boolean sslInitDone;

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            if (sslInitDone) {
                super.channelActive(ctx);
            }
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (!sslInitDone && (evt instanceof SslHandshakeCompletionEvent)) {
                SslHandshakeCompletionEvent e = (SslHandshakeCompletionEvent) evt;
                if (e.isSuccess()) {
                    sslInitDone = true;
                    ctx.fireChannelActive();
                } else {
                    RedisConnection connection = RedisConnection.getFrom(ctx.channel());
                    connection.closeAsync();
                    connection.getConnectionPromise().completeExceptionally(e.cause());
                }
            }
            super.userEventTriggered(ctx, evt);
        }
    });
}
Also used : SslHandshakeCompletionEvent(io.netty.handler.ssl.SslHandshakeCompletionEvent) InputStream(java.io.InputStream) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) javax.net.ssl(javax.net.ssl) KeyStore(java.security.KeyStore) SslHandler(io.netty.handler.ssl.SslHandler) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) SslContext(io.netty.handler.ssl.SslContext) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) RedisConnection(org.redisson.client.RedisConnection)

Aggregations

SslHandler (io.netty.handler.ssl.SslHandler)178 SSLEngine (javax.net.ssl.SSLEngine)63 ChannelPipeline (io.netty.channel.ChannelPipeline)51 Channel (io.netty.channel.Channel)36 SslContext (io.netty.handler.ssl.SslContext)31 ChannelHandler (io.netty.channel.ChannelHandler)28 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)26 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)21 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)19 Test (org.junit.Test)19 SocketChannel (io.netty.channel.socket.SocketChannel)18 IOException (java.io.IOException)17 InetSocketAddress (java.net.InetSocketAddress)16 SSLSession (javax.net.ssl.SSLSession)16 IdleStateHandler (io.netty.handler.timeout.IdleStateHandler)15 SSLParameters (javax.net.ssl.SSLParameters)15 ChannelInitializer (io.netty.channel.ChannelInitializer)14 ChunkedWriteHandler (io.netty.handler.stream.ChunkedWriteHandler)14 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)13 ByteBuf (io.netty.buffer.ByteBuf)13