Example usage for io.netty.handler.ssl SslContext newEngine

List of usage examples for io.netty.handler.ssl SslContext newEngine

Introduction

In this page you can find the example usage for io.netty.handler.ssl SslContext newEngine.

Prototype

public abstract SSLEngine newEngine(ByteBufAllocator alloc);

Source Link

Document

Creates a new SSLEngine .

Usage

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStore.java

License:Open Source License

public HttpBlobStore(URI uri, int timeoutMillis, @Nullable final Credentials creds) throws Exception {
    boolean useTls = uri.getScheme().equals("https");
    if (uri.getPort() == -1) {
        int port = useTls ? 443 : 80;
        uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), port, uri.getPath(), uri.getQuery(),
                uri.getFragment());/*from w ww . j  a va2  s. c o  m*/
    }
    this.uri = uri;
    final SslContext sslCtx;
    if (useTls) {
        // OpenSsl gives us a > 2x speed improvement on fast networks, but requires netty tcnative
        // to be there which is not available on all platforms and environments.
        SslProvider sslProvider = OpenSsl.isAvailable() ? SslProvider.OPENSSL : SslProvider.JDK;
        sslCtx = SslContextBuilder.forClient().sslProvider(sslProvider).build();
    } else {
        sslCtx = null;
    }
    Bootstrap clientBootstrap = new Bootstrap().channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeoutMillis).group(eventLoop)
            .remoteAddress(uri.getHost(), uri.getPort());
    downloadChannels = new SimpleChannelPool(clientBootstrap, new ChannelPoolHandler() {
        @Override
        public void channelReleased(Channel ch) {
            ch.pipeline().remove("read-timeout-handler");
        }

        @Override
        public void channelAcquired(Channel ch) {
            ch.pipeline().addFirst("read-timeout-handler", new ReadTimeoutHandler(timeoutMillis));
        }

        @Override
        public void channelCreated(Channel ch) {
            ChannelPipeline p = ch.pipeline();
            p.addFirst("read-timeout-handler", new ReadTimeoutHandler(timeoutMillis));
            if (sslCtx != null) {
                SSLEngine engine = sslCtx.newEngine(ch.alloc());
                engine.setUseClientMode(true);
                p.addFirst(new SslHandler(engine));
            }
            p.addLast(new HttpClientCodec());
            p.addLast(new HttpDownloadHandler(creds));
        }
    });
    uploadChannels = new SimpleChannelPool(clientBootstrap, new ChannelPoolHandler() {
        @Override
        public void channelReleased(Channel ch) {
        }

        @Override
        public void channelAcquired(Channel ch) {
        }

        @Override
        public void channelCreated(Channel ch) {
            ChannelPipeline p = ch.pipeline();
            if (sslCtx != null) {
                SSLEngine engine = sslCtx.newEngine(ch.alloc());
                engine.setUseClientMode(true);
                p.addFirst(new SslHandler(engine));
            }
            p.addLast(new HttpResponseDecoder());
            // The 10KiB limit was chosen at random. We only expect HTTP servers to respond with
            // an error message in the body and that should always be less than 10KiB.
            p.addLast(new HttpObjectAggregator(10 * 1024));
            p.addLast(new HttpRequestEncoder());
            p.addLast(new ChunkedWriteHandler());
            p.addLast(new HttpUploadHandler(creds));
        }
    });
    this.creds = creds;
}

From source file:com.tc.websocket.server.WebSocketServerInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) throws Exception {

    IConfig cfg = Config.getInstance();// ww  w  . j ava  2  s.  com

    //if we need to check for ByteBuf leaks.
    if (cfg.isLeakDetector()) {
        ResourceLeakDetector.setLevel(Level.ADVANCED);
    }

    //so we get enough data to build our pipeline
    ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(1024));

    ChannelPipeline pipeline = ch.pipeline();

    int incomingPort = ch.localAddress().getPort();

    //if users are coming in on a different port than the proxy port we need to redirect them.
    if (cfg.isProxy() && cfg.getPort() != incomingPort) {
        redirectBuilder.apply(pipeline);
        return;
    }

    if (cfg.isEncrypted()) {
        SslContext sslContext = factory.createSslContext(Config.getInstance());
        SSLEngine engine = sslContext.newEngine(ch.alloc());
        engine.setUseClientMode(false);
        engine.setNeedClientAuth(cfg.isCertAuth());
        ch.pipeline().addFirst("ssl", new SslHandler(engine));
    }

    if (cfg.isProxy()) {
        pipeline.channel().config().setAutoRead(false);
        pipeline.addLast(
                guicer.inject(new ProxyFrontendHandler(cfg.getProxyBackendHost(), cfg.getProxyBackendPort())));

    } else {
        websocketBuilder.apply(pipeline);
    }

}

From source file:org.conscrypt.testing.NettyServer.java

License:Apache License

public void start() {
    group = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(group);// w  w w . j  a v a 2  s.  co m
    b.channel(NioServerSocketChannel.class);
    b.option(SO_BACKLOG, 128);
    b.childOption(SO_KEEPALIVE, true);
    b.childHandler(new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(final Channel ch) throws Exception {
            SslContext context = TestUtil.newNettyServerContext(cipher);
            SSLEngine sslEngine = context.newEngine(ch.alloc());
            ch.pipeline().addFirst(new SslHandler(sslEngine));
            ch.pipeline().addLast(new MessageDecoder());
        }
    });
    // Bind and start to accept incoming connections.
    ChannelFuture future = b.bind(port);
    try {
        future.await();
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
        throw new RuntimeException("Interrupted waiting for bind");
    }
    if (!future.isSuccess()) {
        throw new RuntimeException("Failed to bind", future.cause());
    }
    channel = future.channel();
}

From source file:org.graylog2.plugin.inputs.transports.AbstractTcpTransport.java

License:Open Source License

private Callable<ChannelHandler> buildSslHandlerCallable(SslProvider tlsProvider, File certFile, File keyFile,
        String password, ClientAuth clientAuth, File clientAuthCertFile) {
    return new Callable<ChannelHandler>() {
        @Override/*from w w w.  j  a  v a2 s.c  o  m*/
        public ChannelHandler call() throws Exception {
            try {
                return new SslHandler(createSslEngine());
            } catch (SSLException e) {
                LOG.error(
                        "Error creating SSL context. Make sure the certificate and key are in the correct format: cert=X.509 key=PKCS#8");
                throw e;
            }
        }

        private SSLEngine createSslEngine() throws IOException, CertificateException {
            final X509Certificate[] clientAuthCerts;
            if (EnumSet.of(ClientAuth.OPTIONAL, ClientAuth.REQUIRE).contains(clientAuth)) {
                if (clientAuthCertFile.exists()) {
                    clientAuthCerts = KeyUtil.loadCertificates(clientAuthCertFile.toPath()).stream()
                            .filter(certificate -> certificate instanceof X509Certificate)
                            .map(certificate -> (X509Certificate) certificate).toArray(X509Certificate[]::new);
                } else {
                    LOG.warn(
                            "Client auth configured, but no authorized certificates / certificate authorities configured");
                    clientAuthCerts = null;
                }
            } else {
                clientAuthCerts = null;
            }

            final SslContext sslContext = SslContextBuilder
                    .forServer(certFile, keyFile, Strings.emptyToNull(password)).sslProvider(tlsProvider)
                    .clientAuth(clientAuth).trustManager(clientAuthCerts).build();

            // TODO: Use byte buffer allocator of channel
            return sslContext.newEngine(ByteBufAllocator.DEFAULT);
        }
    };
}

From source file:org.jdiameter.client.impl.transport.tls.netty.StartTlsClientHandler.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//  w w w . j  av a  2 s.c  om
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    logger.debug("StartTlsClientHandler");
    ByteBuf buf = (ByteBuf) msg;
    byte[] bytes = new byte[buf.readableBytes()];
    buf.getBytes(buf.readerIndex(), bytes);

    if ("StartTlsResponse".equals(new String(bytes))) {
        logger.debug("received StartTlsResponse");

        SslContext sslContext = SslContextFactory.getSslContextForClient(this.tlsTransportClient.getConfig());
        SSLEngine sslEngine = sslContext.newEngine(ctx.alloc());
        sslEngine.setUseClientMode(true);
        SslHandler sslHandler = new SslHandler(sslEngine, false);

        final ChannelPipeline pipeline = ctx.pipeline();
        pipeline.remove("startTlsClientHandler");
        pipeline.addLast("sslHandler", sslHandler);

        logger.debug("StartTls starting handshake");

        sslHandler.handshakeFuture().addListener(new GenericFutureListener() {
            @Override
            public void operationComplete(Future future) throws Exception {
                if (future.isSuccess()) {
                    logger.debug("StartTls handshake succesfull");

                    tlsTransportClient.setTlsHandshakingState(TlsHandshakingState.SHAKEN);

                    logger.debug("restoring all handlers");

                    pipeline.addLast("decoder",
                            new DiameterMessageDecoder(
                                    StartTlsClientHandler.this.tlsTransportClient.getParent(),
                                    StartTlsClientHandler.this.tlsTransportClient.getParser()));
                    pipeline.addLast("msgHandler", new DiameterMessageHandler(
                            StartTlsClientHandler.this.tlsTransportClient.getParent(), true));

                    pipeline.addLast("encoder", new DiameterMessageEncoder(
                            StartTlsClientHandler.this.tlsTransportClient.getParser()));
                    pipeline.addLast("inbandWriter", new InbandSecurityHandler());
                }
            }
        });

    }
}

From source file:org.jdiameter.client.impl.transport.tls.netty.StartTlsServerHandler.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//from w w  w  .  j a va 2  s  .com
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    logger.debug("StartTlsServerHandler");
    ByteBuf buf = (ByteBuf) msg;
    byte[] bytes = new byte[buf.readableBytes()];
    buf.getBytes(buf.readerIndex(), bytes);

    if ("StartTlsRequest".equals(new String(bytes))) {
        logger.debug("Received StartTlsRequest");
        SslContext sslContext = SslContextFactory.getSslContextForServer(this.tlsTransportClient.getConfig());
        SSLEngine sslEngine = sslContext.newEngine(ctx.alloc());
        sslEngine.setUseClientMode(false);
        SslHandler sslHandler = new SslHandler(sslEngine, false);

        final ChannelPipeline pipeline = ctx.pipeline();

        pipeline.remove("decoder");
        pipeline.remove("msgHandler");
        pipeline.remove("encoder");
        pipeline.remove("inbandWriter");
        pipeline.remove(this);

        pipeline.addLast("sslHandler", sslHandler);

        sslHandler.handshakeFuture().addListener(new GenericFutureListener() {

            @Override
            public void operationComplete(Future future) throws Exception {
                if (future.isSuccess()) {
                    logger.debug("StartTls server handshake succesfull");

                    tlsTransportClient.setTlsHandshakingState(TlsHandshakingState.SHAKEN);

                    logger.debug("restoring all handlers");

                    pipeline.addLast("decoder",
                            new DiameterMessageDecoder(
                                    StartTlsServerHandler.this.tlsTransportClient.getParent(),
                                    StartTlsServerHandler.this.tlsTransportClient.getParser()));
                    pipeline.addLast("msgHandler", new DiameterMessageHandler(
                            StartTlsServerHandler.this.tlsTransportClient.getParent(), true));

                    pipeline.addLast("encoder", new DiameterMessageEncoder(
                            StartTlsServerHandler.this.tlsTransportClient.getParser()));
                    pipeline.addLast("inbandWriter", new InbandSecurityHandler());

                }
            }
        });

        ReferenceCountUtil.release(msg);
        logger.debug("Sending StartTlsResponse");
        ctx.writeAndFlush(Unpooled.wrappedBuffer("StartTlsResponse".getBytes()))
                .addListener(new GenericFutureListener() {

                    @Override
                    public void operationComplete(Future f) throws Exception {
                        if (!f.isSuccess()) {
                            logger.error(f.cause().getMessage(), f.cause());
                        }

                    }
                });
    } else {
        ctx.fireChannelRead(msg);
    }

}

From source file:org.opendaylight.usc.manager.UscSecureServiceImpl.java

License:Open Source License

@Override
public ChannelOutboundHandler getTcpServerHandler(Channel ch) throws SSLException {
    SslContext sslServerCtx = SslContext.newServerContext(null, trustCertChainFile, null, publicCertChainFile,
            privateKeyFile, null, null, null, IdentityCipherSuiteFilter.INSTANCE, null, 0, 0);
    // mutual authentication as server
    SSLEngine sslServerEngine = sslServerCtx.newEngine(ch.alloc());
    // require client (mutual) authentication
    sslServerEngine.setNeedClientAuth(true);
    return new SslHandler(sslServerEngine);
}

From source file:ratpack.server.internal.DefaultRatpackServer.java

License:Apache License

protected Channel buildChannel(final ServerConfig serverConfig, final ChannelHandler handlerAdapter)
        throws InterruptedException {

    SslContext sslContext = serverConfig.getNettySslContext();
    this.useSsl = sslContext != null;

    ServerBootstrap serverBootstrap = new ServerBootstrap();

    serverConfig.getConnectTimeoutMillis().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, i);
        serverBootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, i);
    });//from   w  w w  . j av  a2s.  c om
    serverConfig.getMaxMessagesPerRead().ifPresent(i -> {
        FixedRecvByteBufAllocator allocator = new FixedRecvByteBufAllocator(i);
        serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, allocator);
        serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, allocator);
    });
    serverConfig.getReceiveBufferSize().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.SO_RCVBUF, i);
        serverBootstrap.childOption(ChannelOption.SO_RCVBUF, i);
    });
    serverConfig.getWriteSpinCount().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.WRITE_SPIN_COUNT, i);
        serverBootstrap.childOption(ChannelOption.WRITE_SPIN_COUNT, i);
    });
    serverConfig.getConnectQueueSize().ifPresent(i -> serverBootstrap.option(ChannelOption.SO_BACKLOG, i));

    return serverBootstrap.group(execController.getEventLoopGroup())
            .channel(ChannelImplDetector.getServerSocketChannelImpl())
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();

                    new ConnectionIdleTimeout(pipeline, serverConfig.getIdleTimeout());

                    if (sslContext != null) {
                        SSLEngine sslEngine = sslContext.newEngine(PooledByteBufAllocator.DEFAULT);
                        pipeline.addLast("ssl", new SslHandler(sslEngine));
                    }

                    pipeline.addLast("decoder", new HttpRequestDecoder(serverConfig.getMaxInitialLineLength(),
                            serverConfig.getMaxHeaderSize(), serverConfig.getMaxChunkSize(), false));
                    pipeline.addLast("encoder", new HttpResponseEncoder());
                    pipeline.addLast("deflater", new IgnorableHttpContentCompressor());
                    pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
                    pipeline.addLast("adapter", handlerAdapter);

                    ch.config().setAutoRead(false);
                }
            }).bind(buildSocketAddress(serverConfig)).sync().channel();
}