Example usage for io.netty.handler.ssl IdentityCipherSuiteFilter INSTANCE

List of usage examples for io.netty.handler.ssl IdentityCipherSuiteFilter INSTANCE

Introduction

In this page you can find the example usage for io.netty.handler.ssl IdentityCipherSuiteFilter INSTANCE.

Prototype

IdentityCipherSuiteFilter INSTANCE

To view the source code for io.netty.handler.ssl IdentityCipherSuiteFilter INSTANCE.

Click Source Link

Document

Defaults to default ciphers when provided ciphers are null

Usage

From source file:com.foilen.smalltools.net.netty.NettyClient.java

License:Open Source License

public void connect(String hostname, int port, final RSATrustedCertificates trustedCertificates,
        final RSACertificate certificate, final List<ChannelHandlerContainer> channelHandlerContainers) {

    AssertTools.assertNull(channel, "Client is already connected");

    try {// w w  w.ja  v  a 2 s  . c  o m
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(NettyCommon.EVENT_LOOP_GROUP);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);

        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel socketChannel) throws Exception {

                // Add sslCtx if needed
                if (trustedCertificates != null || certificate != null) {
                    TrustManagerFactory trustManagerFactory = trustedCertificates == null ? null
                            : RSATools.createTrustManagerFactory(trustedCertificates);
                    KeyManagerFactory keyManagerFactory = certificate == null ? null
                            : RSATools.createKeyManagerFactory(certificate);

                    CipherSuiteFilter cipherFilter = IdentityCipherSuiteFilter.INSTANCE;
                    SslContext sslCtx = SslContext.newClientContext(SslProvider.JDK, null, trustManagerFactory,
                            null, null, null, keyManagerFactory, null, cipherFilter, null, 0, 0);
                    socketChannel.pipeline().addLast(sslCtx.newHandler(socketChannel.alloc()));
                }

                // Add the channel handlers
                for (ChannelHandlerContainer channelHandlerContainer : channelHandlerContainers) {
                    socketChannel.pipeline()
                            .addLast(ReflectionTools.instantiate(
                                    channelHandlerContainer.getChannelHandlerClass(),
                                    channelHandlerContainer.getConstructorParams()));
                }

            }
        });

        logger.info("Connecting to {}:{}", hostname, port);
        channel = bootstrap.connect(hostname, port).sync().channel();
    } catch (InterruptedException e) {
        logger.info("Connection to {}:{} was interrupted while being created", hostname, port);
        throw new SmallToolsException("Connection was interrupted");
    }

}

From source file:com.foilen.smalltools.net.netty.NettyServer.java

License:Open Source License

/**
 * Start the server.//from  w  w  w .  j a v  a 2 s . com
 *
 * @param port
 *            the port to listen on (0 for a random port ; get it with {@link #getPort()})
 * @param trustedCertificates
 *            (optional) the certificate to trust connections from
 * @param certificate
 *            (optional) the server's certificate
 * @param channelHandlerContainers
 *            the channel handlers for the incoming connections
 */
public void start(final int port, final RSATrustedCertificates trustedCertificates,
        final RSACertificate certificate, final List<ChannelHandlerContainer> channelHandlerContainers) {

    AssertTools.assertNull(thread, "Server is already started");

    final CountDownLatch countDownLatch = new CountDownLatch(1);
    thread = new Thread(() -> {
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(NettyCommon.EVENT_LOOP_GROUP, NettyCommon.EVENT_LOOP_GROUP);
            serverBootstrap.channel(NioServerSocketChannel.class);

            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {

                    InetSocketAddress remoteAddress = socketChannel.remoteAddress();
                    logger.info("Got a connection from {}:{}", remoteAddress.getHostName(),
                            remoteAddress.getPort());

                    // Add sslCtx if needed
                    if (trustedCertificates != null || certificate != null) {
                        TrustManagerFactory trustManagerFactory = trustedCertificates == null ? null
                                : RSATools.createTrustManagerFactory(trustedCertificates);
                        KeyManagerFactory keyManagerFactory = certificate == null ? null
                                : RSATools.createKeyManagerFactory(certificate);

                        CipherSuiteFilter cipherFilter = IdentityCipherSuiteFilter.INSTANCE;
                        SslContext sslCtx = SslContext.newServerContext(SslProvider.JDK, null,
                                trustManagerFactory, null, null, null, keyManagerFactory, null, cipherFilter,
                                null, 0, 0);
                        SslHandler sslHandler = sslCtx.newHandler(socketChannel.alloc());

                        if (trustManagerFactory == null) {
                            logger.debug("Will not verify client's identity");
                        } else {
                            logger.debug("Will verify client's identity");
                            SSLEngine sslEngine = sslHandler.engine();
                            sslEngine.setNeedClientAuth(true);
                        }

                        socketChannel.pipeline().addLast(sslHandler);
                    }

                    // Add the channel handlers
                    for (ChannelHandlerContainer channelHandlerContainer : channelHandlerContainers) {
                        socketChannel.pipeline()
                                .addLast(ReflectionTools.instantiate(
                                        channelHandlerContainer.getChannelHandlerClass(),
                                        channelHandlerContainer.getConstructorParams()));
                    }
                }
            }) //
                    .option(ChannelOption.SO_BACKLOG, 128) //
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            bindedPort = port;
            logger.info("Server on port {} is starting...", port);
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            SocketAddress socketAddress = channelFuture.channel().localAddress();
            if (socketAddress instanceof InetSocketAddress) {
                InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
                bindedPort = inetSocketAddress.getPort();
            }
            logger.info("Server on port {} is started", bindedPort);
            countDownLatch.countDown();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            logger.info("Server on port {} is interrupted", bindedPort);
        } finally {
            countDownLatch.countDown();
        }
        logger.info("Server on port {} is stopped", bindedPort);
    });
    thread.setName("Netty Server-" + bindedPort);
    thread.start();

    try {
        countDownLatch.await();
    } catch (InterruptedException e) {
        logger.error("Interrupted while waiting for the server to start");
    }
}

From source file:com.linkedin.r2.transport.http.client.Http2InitializerHandler.java

License:Apache License

/**
 * Sets up HTTP/2 over TLS through ALPN (h2) pipeline
 *///from  w  w w .j av  a 2 s .  com
private void configureHttpsPipeline(ChannelHandlerContext ctx) throws Exception {
    JdkSslContext context = new JdkSslContext(_sslContext, IS_CLIENT,
            Arrays.asList(_sslParameters.getCipherSuites()), IdentityCipherSuiteFilter.INSTANCE,
            new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                    ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                    ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                    ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1),
            _sslParameters.getNeedClientAuth() ? ClientAuth.REQUIRE : ClientAuth.OPTIONAL);
    SslHandler sslHandler = context.newHandler(ctx.alloc());

    Http2StreamCodec http2Codec = new Http2StreamCodecBuilder().connection(_connection)
            .maxContentLength(_maxResponseSize).maxHeaderSize(_maxHeaderSize)
            .gracefulShutdownTimeoutMillis(_gracefulShutdownTimeout).streamingTimeout(_streamingTimeout)
            .scheduler(_scheduler).build();

    Http2AlpnHandler alpnHandler = new Http2AlpnHandler(sslHandler, http2Codec);
    Http2SchemeHandler schemeHandler = new Http2SchemeHandler(HttpScheme.HTTPS.toString());
    Http2StreamResponseHandler responseHandler = new Http2StreamResponseHandler();
    Http2ChannelPoolHandler channelPoolHandler = new Http2ChannelPoolHandler();

    ctx.pipeline().addBefore(ctx.name(), "alpnHandler", alpnHandler);
    ctx.pipeline().addBefore(ctx.name(), "schemeHandler", schemeHandler);
    ctx.pipeline().addBefore(ctx.name(), "responseHandler", responseHandler);
    ctx.pipeline().addBefore(ctx.name(), "channelHandler", channelPoolHandler);

    _setupComplete = true;
}

From source file:io.aos.netty5.spdy.client.SpdyClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx = SslContext.newClientContext(null, InsecureTrustManagerFactory.INSTANCE, null,
            IdentityCipherSuiteFilter.INSTANCE,
            Arrays.asList(SelectedProtocol.SPDY_3_1.protocolName(), SelectedProtocol.HTTP_1_1.protocolName()),
            JettyNpnSslEngineWrapper.instance(), 0, 0);

    HttpResponseClientHandler httpResponseHandler = new HttpResponseClientHandler();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {/*w  w w. ja  v a2s.com*/
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(new SpdyClientInitializer(sslCtx, httpResponseHandler));

        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to " + HOST + ':' + PORT);

        // Create a GET request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "");
        request.headers().set(HttpHeaders.Names.HOST, HOST);
        request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

        // Send the GET request.
        channel.writeAndFlush(request).sync();

        // Waits for the complete HTTP response
        httpResponseHandler.queue().take().sync();
        System.out.println("Finished SPDY HTTP GET");

        // Wait until the connection is closed.
        channel.close().syncUninterruptibly();
    } finally {
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
    }
}

From source file:io.aos.netty5.spdy.server.SpdyServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey(), null, null,
            IdentityCipherSuiteFilter.INSTANCE,
            Arrays.asList(SelectedProtocol.SPDY_3_1.protocolName(), SelectedProtocol.HTTP_1_1.protocolName()),
            JettyNpnSslEngineWrapper.instance(), 0, 0);

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//w  w  w .j a va 2s  .  c  o  m
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new SpdyServerInitializer(sslCtx));

        Channel ch = b.bind(PORT).sync().channel();

        System.err
                .println("Open your SPDY-enabled web browser and navigate to https://127.0.0.1:" + PORT + '/');
        System.err.println("If using Chrome browser, check your SPDY sessions at chrome://net-internals/#spdy");

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:org.apache.zookeeper.common.SSLContextAndOptions.java

License:Apache License

public SslContext createNettyJdkSslContext(SSLContext sslContext, boolean isClientSocket) {
    return new JdkSslContext(sslContext, isClientSocket, cipherSuitesAsList, IdentityCipherSuiteFilter.INSTANCE,
            null,// w w  w . ja va 2  s.c  o m
            isClientSocket ? X509Util.ClientAuth.NONE.toNettyClientAuth() : clientAuth.toNettyClientAuth(),
            enabledProtocols, false);
}

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:org.opendaylight.usc.manager.UscSecureServiceImpl.java

License:Open Source License

@Override
public ChannelOutboundHandler getTcpClientHandler(Channel ch) throws SSLException {
    SslContext sslClientCtx = SslContext.newClientContext(null, trustCertChainFile, null, publicCertChainFile,
            privateKeyFile, null, null, null, IdentityCipherSuiteFilter.INSTANCE, null, 0, 0);
    // mutual authentication as client
    return sslClientCtx.newHandler(ch.alloc());
}

From source file:org.ow2.petals.bc.gateway.commons.handlers.AuthenticatorSSLHandler.java

License:Open Source License

private void setUpSslHandlers(final ChannelHandlerContext ctx, final AbstractDomain domain,
        final @Nullable String certificate, final @Nullable String key, final @Nullable String passphrase,
        final @Nullable String remoteCertificate) throws SSLException {

    // TODO could we use certificate only for auth and not encryption?
    // TODO support openssl
    final SslHandler sslHandler;
    if (pdOrAuth.isB() && certificate != null && key != null) {
        // server side ssl, do not forget startTls so that our accept can be sent after the handler is added

        final ServiceUnitDataHandler handler = domain.getSUHandler();

        final SslContextBuilder builder = SslContextBuilder
                .forServer(ServiceUnitUtil.getFile(handler.getInstallRoot(), certificate),
                        ServiceUnitUtil.getFile(handler.getInstallRoot(), key), passphrase)
                .sslProvider(SslProvider.JDK).ciphers(null, IdentityCipherSuiteFilter.INSTANCE)
                .sessionCacheSize(0).sessionTimeout(0);

        if (remoteCertificate != null) {
            builder.trustManager(ServiceUnitUtil.getFile(handler.getInstallRoot(), remoteCertificate))
                    .clientAuth(ClientAuth.REQUIRE);
        }//from w  w w  .ja v a  2  s .com

        // until https://github.com/netty/netty/issues/5170 is accepted
        // we need to create the handler by hand
        sslHandler = new SslHandler(builder.build().newEngine(ctx.alloc()), true);
    } else if (pdOrAuth.isA() && remoteCertificate != null) {
        // client side

        final String installRoot = domain.getSUHandler().getInstallRoot();
        final SslContextBuilder builder = SslContextBuilder.forClient().sslProvider(SslProvider.JDK)
                .trustManager(ServiceUnitUtil.getFile(installRoot, remoteCertificate))
                .ciphers(null, IdentityCipherSuiteFilter.INSTANCE).sessionCacheSize(0).sessionTimeout(0);

        if (certificate != null && key != null) {
            builder.keyManager(ServiceUnitUtil.getFile(installRoot, certificate),
                    ServiceUnitUtil.getFile(installRoot, key), passphrase);
        }

        sslHandler = builder.build().newHandler(ctx.alloc());
    } else {
        sslHandler = null;
    }

    // For a server, it contains the transporter name and the consumer domain name (it was updated in channelRead0)
    // For a client, it contains the provider domain name (it was set by the component)
    final String logName = logger.getName();

    // let's replace the debug logger with something specific to this consumer
    ctx.pipeline().replace(HandlerConstants.LOG_DEBUG_HANDLER, HandlerConstants.LOG_DEBUG_HANDLER,
            new LoggingHandler(logName, LogLevel.TRACE));

    ctx.pipeline().replace(HandlerConstants.LOG_ERRORS_HANDLER, HandlerConstants.LOG_ERRORS_HANDLER,
            new LastLoggingHandler(logName + ".errors"));

    if (sslHandler != null) {
        // if there is a sslHandler, then we can only add the domain handler after the handshake is finished
        // if not we risk sending things too early in it

        sslHandler.handshakeFuture().addListener(new FutureListener<Channel>() {
            @Override
            public void operationComplete(final @Nullable Future<Channel> future) throws Exception {
                assert future != null;
                if (!future.isSuccess()) {
                    authenticationFuture.setFailure(future.cause());
                } else {
                    // I must keep the handler here until now in case there is an exception so that I can log it
                    ctx.pipeline().replace(HandlerConstants.DOMAIN_HANDLER, HandlerConstants.DOMAIN_HANDLER,
                            dhb.build(domain));
                    authenticationFuture.setSuccess(ctx.channel());
                }
            }
        });

        ctx.pipeline().addAfter(HandlerConstants.LOG_DEBUG_HANDLER, HandlerConstants.SSL_HANDLER, sslHandler);
    }

    if (pdOrAuth.isB()) {
        if (logger.isLoggable(Level.FINE)) {
            logger.fine("Sending an Accept (" + ctx.channel().remoteAddress() + ")");
        }

        // this must be sent after the ssh handler is replaced (when using ssl) so that we are ready to receive ssl data right away
        // but this must be sent before the domain handler is replaced (when not using ssl), because it will send
        // data and it must arrive AFTER our Accept
        ctx.writeAndFlush(new AuthAccept());
    }

    // else it is done in the FutureListener
    if (sslHandler == null) {
        ctx.pipeline().replace(HandlerConstants.DOMAIN_HANDLER, HandlerConstants.DOMAIN_HANDLER,
                dhb.build(domain));
        authenticationFuture.setSuccess(ctx.channel());
    }
}