Example usage for io.netty.handler.ssl SslHandler SslHandler

List of usage examples for io.netty.handler.ssl SslHandler SslHandler

Introduction

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

Prototype

public SslHandler(SSLEngine engine) 

Source Link

Document

Creates a new instance which runs all delegated tasks directly on the EventExecutor .

Usage

From source file:org.opendaylight.ocpjava.protocol.impl.core.TcpChannelInitializer.java

License:Open Source License

@Override
protected void initChannel(final SocketChannel ch) {
    if (ch.remoteAddress() != null) {
        InetAddress radioHeadAddress = ch.remoteAddress().getAddress();
        int port = ch.localAddress().getPort();
        int remotePort = ch.remoteAddress().getPort();
        LOG.debug("Incoming connection from (remote address): {}:{} --> :{}", radioHeadAddress.toString(),
                remotePort, port);/*from w ww  . jav a2  s  .  c  o  m*/

        if (!getRadioHeadConnectionHandler().accept(radioHeadAddress)) {
            ch.disconnect();
            LOG.debug("Incoming connection rejected");
            return;
        }
    }
    LOG.debug("Incoming connection accepted - building pipeline");
    allChannels.add(ch);
    ConnectionFacade connectionFacade = null;
    connectionFacade = connectionAdapterFactory.createConnectionFacade(ch, null);
    try {
        LOG.trace("initChannel - getRadioHeadConnectionHandler: {}", getRadioHeadConnectionHandler());
        getRadioHeadConnectionHandler().onRadioHeadConnected(connectionFacade);
        connectionFacade.checkListeners();
        ch.pipeline().addLast(PipelineHandlers.IDLE_HANDLER.name(),
                new IdleHandler(getRadioHeadIdleTimeout(), TimeUnit.MILLISECONDS));
        boolean tlsPresent = false;

        // If this channel is configured to support SSL it will only support SSL
        if (getTlsConfiguration() != null) {
            tlsPresent = true;
            SslContextFactory sslFactory = new SslContextFactory(getTlsConfiguration());
            SSLEngine engine = sslFactory.getServerContext().createSSLEngine();
            engine.setNeedClientAuth(true);
            engine.setUseClientMode(false);
            ch.pipeline().addLast(PipelineHandlers.SSL_HANDLER.name(), new SslHandler(engine));
        }

        ch.pipeline().addLast(PipelineHandlers.OCP_XML_DECODER.name(),
                new OCPXmlDecoder(connectionFacade, tlsPresent));
        LOG.trace("TcpChannelInitializer - initChannel OCPXmlDecoder()");

        OCPDecoder ocpDecoder = new OCPDecoder();
        ocpDecoder.setDeserializationFactory(getDeserializationFactory());
        ch.pipeline().addLast(PipelineHandlers.OCP_DECODER.name(), ocpDecoder);
        LOG.trace("TcpChannelInitializer - initChannel ocpDecoder()");

        OCPEncoder ocpEncoder = new OCPEncoder();
        ocpEncoder.setSerializationFactory(getSerializationFactory());
        ch.pipeline().addLast(PipelineHandlers.OCP_ENCODER.name(), ocpEncoder);
        LOG.trace("TcpChannelInitializer - initChannel ocpEncoder()");

        ch.pipeline().addLast(PipelineHandlers.DELEGATING_INBOUND_HANDLER.name(),
                new DelegatingInboundHandler(connectionFacade));
        LOG.trace("TcpChannelInitializer - initChannel DelegatingInboundHandler()");

        if (!tlsPresent) {
            connectionFacade.fireConnectionReadyNotification();
        }
        LOG.trace("TcpChannelInitializer - initChannel End");
    } catch (Exception e) {
        LOG.warn("Failed to initialize channel", e);
        ch.close();
    }
}

From source file:org.opendaylight.openflowjava.protocol.impl.clients.SimpleClientInitializer.java

License:Open Source License

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    if (secured) {
        SSLEngine engine = SslContextFactory.getClientContext().createSSLEngine();
        engine.setUseClientMode(true);//ww  w .  j  av  a  2 s  .c o m
        pipeline.addLast("ssl", new SslHandler(engine));
        pipeline.addLast("framer", new SimpleClientFramer());
    }
    SimpleClientHandler simpleClientHandler = new SimpleClientHandler(isOnlineFuture, scenarioHandler);
    simpleClientHandler.setScenario(scenarioHandler);
    pipeline.addLast("handler", simpleClientHandler);
    isOnlineFuture = null;

}

From source file:org.opendaylight.openflowjava.protocol.impl.core.TcpChannelInitializer.java

License:Open Source License

@Override
protected void initChannel(final SocketChannel ch) {
    if (ch.remoteAddress() != null) {
        final InetAddress switchAddress = ch.remoteAddress().getAddress();
        final int port = ch.localAddress().getPort();
        final int remotePort = ch.remoteAddress().getPort();
        LOG.debug("Incoming connection from (remote address): {}:{} --> :{}", switchAddress.toString(),
                remotePort, port);/*from   w w  w .  java 2s .  c o m*/

        if (!getSwitchConnectionHandler().accept(switchAddress)) {
            ch.disconnect();
            LOG.debug("Incoming connection rejected");
            return;
        }
    }
    LOG.debug("Incoming connection accepted - building pipeline");
    allChannels.add(ch);
    ConnectionFacade connectionFacade = null;
    connectionFacade = connectionAdapterFactory.createConnectionFacade(ch, null, useBarrier());
    try {
        LOG.debug("Calling OF plugin: {}", getSwitchConnectionHandler());
        getSwitchConnectionHandler().onSwitchConnected(connectionFacade);
        connectionFacade.checkListeners();
        ch.pipeline().addLast(PipelineHandlers.IDLE_HANDLER.name(),
                new IdleHandler(getSwitchIdleTimeout(), TimeUnit.MILLISECONDS));
        boolean tlsPresent = false;

        // If this channel is configured to support SSL it will only support SSL
        if (getTlsConfiguration() != null) {
            tlsPresent = true;
            final SslContextFactory sslFactory = new SslContextFactory(getTlsConfiguration());
            final SSLEngine engine = sslFactory.getServerContext().createSSLEngine();
            engine.setNeedClientAuth(true);
            engine.setUseClientMode(false);
            List<String> suitesList = getTlsConfiguration().getCipherSuites();
            if (suitesList != null && !suitesList.isEmpty()) {
                LOG.debug("Requested Cipher Suites are: {}", suitesList);
                String[] suites = suitesList.toArray(new String[suitesList.size()]);
                engine.setEnabledCipherSuites(suites);
                LOG.debug("Cipher suites enabled in SSLEngine are: {}",
                        engine.getEnabledCipherSuites().toString());
            }
            final SslHandler ssl = new SslHandler(engine);
            final Future<Channel> handshakeFuture = ssl.handshakeFuture();
            final ConnectionFacade finalConnectionFacade = connectionFacade;
            handshakeFuture.addListener(new GenericFutureListener<Future<? super Channel>>() {
                @Override
                public void operationComplete(final Future<? super Channel> future) throws Exception {
                    finalConnectionFacade.fireConnectionReadyNotification();
                }
            });
            ch.pipeline().addLast(PipelineHandlers.SSL_HANDLER.name(), ssl);
        }
        ch.pipeline().addLast(PipelineHandlers.OF_FRAME_DECODER.name(),
                new OFFrameDecoder(connectionFacade, tlsPresent));
        ch.pipeline().addLast(PipelineHandlers.OF_VERSION_DETECTOR.name(), new OFVersionDetector());
        final OFDecoder ofDecoder = new OFDecoder();
        ofDecoder.setDeserializationFactory(getDeserializationFactory());
        ch.pipeline().addLast(PipelineHandlers.OF_DECODER.name(), ofDecoder);
        final OFEncoder ofEncoder = new OFEncoder();
        ofEncoder.setSerializationFactory(getSerializationFactory());
        ch.pipeline().addLast(PipelineHandlers.OF_ENCODER.name(), ofEncoder);
        ch.pipeline().addLast(PipelineHandlers.DELEGATING_INBOUND_HANDLER.name(),
                new DelegatingInboundHandler(connectionFacade));
        if (!tlsPresent) {
            connectionFacade.fireConnectionReadyNotification();
        }
    } catch (final Exception e) {
        LOG.warn("Failed to initialize channel", e);
        ch.close();
    }
}

From source file:org.opendaylight.openflowjava.protocol.impl.core.TlsDetector.java

License:Open Source License

private static void enableSsl(ChannelHandlerContext ctx) {
    if (ctx.pipeline().get(COMPONENT_NAMES.SSL_HANDLER.name()) == null) {
        LOGGER.trace("Engaging TLS handler");
        ChannelPipeline p = ctx.channel().pipeline();
        SSLEngine engine = SslContextFactory.getServerContext().createSSLEngine();
        engine.setUseClientMode(false);/*  w w w .  j  a  va2 s  .co  m*/
        p.addAfter(COMPONENT_NAMES.TLS_DETECTOR.name(), COMPONENT_NAMES.SSL_HANDLER.name(),
                new SslHandler(engine));
    }
}

From source file:org.opendaylight.ovsdb.lib.impl.OvsdbConnectionService.java

License:Open Source License

@Override
public OvsdbClient connectWithSsl(final InetAddress address, final int port, final SSLContext sslContext) {
    try {//  w  w w .ja  va  2  s. c o  m
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup());
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));

        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel channel) throws Exception {
                if (sslContext != null) {
                    /* First add ssl handler if ssl context is given */
                    SSLEngine engine = sslContext.createSSLEngine(address.toString(), port);
                    engine.setUseClientMode(true);
                    channel.pipeline().addLast("ssl", new SslHandler(engine));
                }
                channel.pipeline().addLast(
                        //new LoggingHandler(LogLevel.INFO),
                        new JsonRpcDecoder(100000), new StringEncoder(CharsetUtil.UTF_8),
                        new ExceptionHandler());
            }
        });

        ChannelFuture future = bootstrap.connect(address, port).sync();
        Channel channel = future.channel();
        OvsdbClient client = getChannelClient(channel, ConnectionType.ACTIVE,
                Executors.newFixedThreadPool(NUM_THREADS));
        return client;
    } catch (InterruptedException e) {
        System.out.println("Thread was interrupted during connect");
    }
    return null;
}

From source file:org.opendaylight.ovsdb.lib.impl.OvsdbConnectionService.java

License:Open Source License

/**
 * OVSDB Passive listening thread that uses Netty ServerBootstrap to open
 * passive connection with Ssl and handle channel callbacks.
 *//*  ww  w. ja v  a2 s.  c o  m*/
private static void ovsdbManagerWithSsl(int port, final SSLContext sslContext) {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel channel) throws Exception {
                        logger.debug("New Passive channel created : {}", channel);
                        if (sslContext != null) {
                            /* Add SSL handler first if SSL context is provided */
                            SSLEngine engine = sslContext.createSSLEngine();
                            engine.setUseClientMode(false); // work in a server mode
                            engine.setNeedClientAuth(true); // need client authentication
                            channel.pipeline().addLast("ssl", new SslHandler(engine));
                        }

                        channel.pipeline().addLast(new JsonRpcDecoder(100000),
                                new StringEncoder(CharsetUtil.UTF_8), new ExceptionHandler());

                        handleNewPassiveConnection(channel);
                    }
                });
        serverBootstrap.option(ChannelOption.TCP_NODELAY, true);
        serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
                new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
        // Start the server.
        ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
        Channel serverListenChannel = channelFuture.channel();
        // Wait until the server socket is closed.
        serverListenChannel.closeFuture().sync();
    } catch (InterruptedException e) {
        logger.error("Thread interrupted", e);
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:org.opendaylight.protocol.pcep.impl.AbstractPCEPSessionNegotiator.java

License:Open Source License

private boolean handleMessageStartTlsWait(final Message msg) {
    if (msg instanceof Starttls) {
        final SslContextFactory sslFactory = new SslContextFactory(this.tlsConfiguration);
        final SSLContext sslContext = sslFactory.getServerContext();
        if (sslContext == null) {
            this.sendErrorMessage(PCEPErrors.NOT_POSSIBLE_WITHOUT_TLS);
            negotiationFailed(new IllegalStateException("Failed to establish a TLS connection."));
            this.state = State.FINISHED;
            return true;
        }//from   w w w. ja  v a 2 s  . c om
        final SSLEngine engine = sslContext.createSSLEngine();
        engine.setNeedClientAuth(true);
        engine.setUseClientMode(false);
        this.channel.pipeline().addFirst(new SslHandler(engine));
        LOG.info("PCEPS TLS connection with peer: {} established succesfully.", this.channel);
        startNegotiationWithOpen();
        return true;
    } else if (!(msg instanceof Pcerr)) {
        this.sendErrorMessage(PCEPErrors.NON_STARTTLS_MSG_RCVD);
        negotiationFailed(new IllegalStateException("Unexpected message recieved."));
        this.state = State.FINISHED;
        return true;
    }
    return 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.ratpackframework.server.internal.RatpackChannelInitializer.java

License:Apache License

public void initChannel(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();

    if (sslContext != null) {
        SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(false);/*  www . j av a 2  s  .co m*/
        pipeline.addLast("ssl", new SslHandler(engine));
    }

    pipeline.addLast("decoder", new HttpRequestDecoder());
    pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
    pipeline.addLast("encoder", new HttpResponseEncoder());
    pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
    pipeline.addLast("handler", nettyHandlerAdapter);
}

From source file:org.redisson.client.handler.RedisChannelInitializer.java

License:Apache License

private void initSsl(final RedisClientConfig config, Channel ch) throws KeyStoreException, IOException,
        NoSuchAlgorithmException, CertificateException, SSLException, UnrecoverableKeyException {
    if (!config.getAddress().isSsl()) {
        return;/*from  w  w  w .  java  2s  .  c o  m*/
    }

    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);
    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()) {
        // TODO remove for JDK 1.7+
        try {
            Method method = sslParams.getClass().getDeclaredMethod("setEndpointIdentificationAlgorithm",
                    String.class);
            method.invoke(sslParams, "HTTPS");
        } catch (Exception e) {
            throw new SSLException(e);
        }
    } 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.getConnectionPromise().tryFailure(e.cause());
                }
            }

            super.userEventTriggered(ctx, evt);
        }

    });
}