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:it.jnrpe.JNRPE.java

License:Apache License

/**
 * Creates and returns a configured NETTY ServerBootstrap object.
 * //from w w w. j av  a  2 s  .c  o m
 * @param useSSL
 *            <code>true</code> if SSL must be used.
        
 * @return the server bootstrap object */
private ServerBootstrap getServerBootstrap(final boolean useSSL) {

    final CommandInvoker invoker = new CommandInvoker(pluginRepository, commandRepository, acceptParams,
            getExecutionContext());

    final ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(final SocketChannel ch) throws Exception {

                    if (useSSL) {
                        final SSLEngine engine = getSSLEngine();
                        engine.setEnabledCipherSuites(engine.getSupportedCipherSuites());
                        engine.setUseClientMode(false);
                        engine.setNeedClientAuth(false);
                        ch.pipeline().addLast("ssl", new SslHandler(engine));
                    }

                    ch.pipeline()
                            .addLast(new JNRPERequestDecoder(), new JNRPEResponseEncoder(),
                                    new JNRPEServerHandler(invoker, context))
                            .addLast("idleStateHandler", new IdleStateHandler(readTimeout, writeTimeout, 0))
                            .addLast("jnrpeIdleStateHandler", new JNRPEIdleStateHandler(context));
                }
            }).option(ChannelOption.SO_BACKLOG, maxAcceptedConnections)
            .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);

    return serverBootstrap;
}

From source file:jetty.cdi.CDINettyJaxrsServer.java

License:Apache License

@Override
public void start() {
    eventLoopGroup = new NioEventLoopGroup(ioWorkerCount);
    eventExecutor = new NioEventLoopGroup(executorThreadCount);
    deployment.start();//from w ww. j a  va2s  .  c  o m
    // this is the only line that's different in the whole class.
    final RequestDispatcher dispatcher = this.createRequestDispatcher();
    // Configure the server.
    if (sslContext == null) {
        bootstrap.group(eventLoopGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new HttpRequestDecoder());
                        ch.pipeline().addLast(new HttpObjectAggregator(maxRequestSize));
                        ch.pipeline().addLast(new HttpResponseEncoder());
                        ch.pipeline().addLast(new RestEasyHttpRequestDecoder(dispatcher.getDispatcher(), root,
                                RestEasyHttpRequestDecoder.Protocol.HTTP));
                        ch.pipeline().addLast(new RestEasyHttpResponseEncoder(dispatcher));
                        ch.pipeline().addLast(eventExecutor, new RequestHandler(dispatcher));
                    }
                }).option(ChannelOption.SO_BACKLOG, backlog).childOption(ChannelOption.SO_KEEPALIVE, true);
    } else {
        final SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(false);
        bootstrap.group(eventLoopGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addFirst(new SslHandler(engine));
                        ch.pipeline().addLast(new HttpRequestDecoder());
                        ch.pipeline().addLast(new HttpObjectAggregator(maxRequestSize));
                        ch.pipeline().addLast(new HttpResponseEncoder());
                        ch.pipeline().addLast(new RestEasyHttpRequestDecoder(dispatcher.getDispatcher(), root,
                                RestEasyHttpRequestDecoder.Protocol.HTTPS));
                        ch.pipeline().addLast(new RestEasyHttpResponseEncoder(dispatcher));
                        ch.pipeline().addLast(eventExecutor, new RequestHandler(dispatcher));

                    }
                }).option(ChannelOption.SO_BACKLOG, backlog).childOption(ChannelOption.SO_KEEPALIVE, true);
    }

    bootstrap.bind(port).syncUninterruptibly();
}

From source file:net.floodlightcontroller.core.internal.OFChannelInitializer.java

License:Apache License

@Override
protected void initChannel(Channel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    OFChannelHandler handler = new OFChannelHandler(switchManager, connectionListener, pipeline, debugCounters,
            timer, ofBitmaps, defaultFactory);

    if (keyStore != null && keyStorePassword != null) {
        try {/*from  w w  w  .  j  a v  a2 s.  co  m*/
            /* Set up factories and stores. */
            TrustManagerFactory tmFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            KeyStore tmpKS = null;
            tmFactory.init(tmpKS);

            /* Use keystore/pass defined in properties file. */
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(new FileInputStream(keyStore), keyStorePassword.toCharArray());

            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(ks, keyStorePassword.toCharArray());

            KeyManager[] km = kmf.getKeyManagers();
            TrustManager[] tm = tmFactory.getTrustManagers();

            /* Set up SSL prereqs for Netty. */
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(km, tm, null);
            SSLEngine sslEngine = sslContext.createSSLEngine();

            /* We are the server and we will create secure sessions. */
            sslEngine.setUseClientMode(false);
            sslEngine.setEnableSessionCreation(true);

            /* These are redundant (default), but for clarity... */
            sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
            sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());

            /* First, decrypt w/handler+engine; then, proceed with rest of handlers. */
            pipeline.addLast(PipelineHandler.SSL_TLS_ENCODER_DECODER, new SslHandler(sslEngine));
            log.info("SSL OpenFlow socket initialized and handler ready for switch.");
        } catch (Exception e) { /* There are lots of possible exceptions to catch, so this should get them all. */
            log.error("Exception initializing SSL OpenFlow socket: {}", e.getMessage());
            throw e; /* If we wanted secure but didn't get it, we should bail. */
        }
    }

    pipeline.addLast(PipelineHandler.OF_MESSAGE_DECODER, new OFMessageDecoder());
    pipeline.addLast(PipelineHandler.OF_MESSAGE_ENCODER, new OFMessageEncoder());
    pipeline.addLast(PipelineHandler.MAIN_IDLE,
            new IdleStateHandler(PipelineIdleReadTimeout.MAIN, PipelineIdleWriteTimeout.MAIN, 0));
    pipeline.addLast(PipelineHandler.READ_TIMEOUT, new ReadTimeoutHandler(30));
    pipeline.addLast(PipelineHandler.CHANNEL_HANDSHAKE_TIMEOUT,
            new HandshakeTimeoutHandler(handler, timer, PipelineHandshakeTimeout.CHANNEL));

    pipeline.addLast(PipelineHandler.CHANNEL_HANDLER, handler);
}

From source file:net.petercashel.nettyCore.client.clientCore.java

License:Apache License

public static SslHandler getClientSSLHandler(final String addr, final int port) {
    final SSLEngine sslEngine = SSLContextProvider.get().createSSLEngine(addr, port);
    sslEngine.setUseClientMode(true);// w ww.  j  a va 2 s  .co m
    final SslHandler sslHandler = new SslHandler(sslEngine);
    return sslHandler;
}

From source file:net.petercashel.nettyCore.server.serverCore.java

License:Apache License

public static SslHandler getSSLHandler() {
    final SSLEngine sslEngine = SSLContextProvider.get().createSSLEngine();
    sslEngine.setUseClientMode(false);//www. j  a v  a  2s .  c o  m
    sslEngine.setNeedClientAuth(false);
    final SslHandler sslHandler = new SslHandler(sslEngine);

    return sslHandler;
}

From source file:netty.server.WebSocketSslServerInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    SSLEngine engine = WebSocketSslServerSslContext.getInstance().serverContext().createSSLEngine();
    engine.setUseClientMode(false);//  ww  w  . j  a  v a 2 s .co m
    pipeline.addLast("ssl", new SslHandler(engine));
    pipeline.addLast("encoder", new HttpResponseEncoder());
    pipeline.addLast("decoder", new HttpRequestDecoder());
    pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
    pipeline.addLast("handler", new WebSocketSslServerHandler());
}

From source file:nikoladasm.aspark.server.ServerInitializer.java

License:Open Source License

@Override
public void initChannel(SocketChannel channel) throws Exception {
    ChannelPipeline pipeline = channel.pipeline();
    if (sslContext != null) {
        SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
        sslEngine.setWantClientAuth(true);
        sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
        sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
        sslEngine.setEnableSessionCreation(true);
        SslHandler sslHandler = new SslHandler(sslEngine);
        pipeline.addLast("ssl", sslHandler);
    }//w w  w  .j  a va  2 s . com
    pipeline.addLast("httpCodec", new HttpServerCodec());
    pipeline.addLast("inflater", new HttpContentDecompressor());
    pipeline.addLast("deflater", new HttpContentCompressor());
    pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
    pipeline.addLast("aggregator", new HttpObjectAggregator(maxContentLength));
    ServerHandler serverHandler = new ServerHandler(ipAddress, port, dispatcher, exceptionMap, webSockets,
            serverName, pool);
    pipeline.addLast("handler", serverHandler);
}

From source file:nss.delta.agentmanager.dummycon.OFChannelInitializer.java

License:Apache License

@Override
protected void initChannel(Channel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    OFChannelHandler newhandler = new OFChannelHandler(pipeline, timer, ofBitmaps, defaultFactory,
            testHandShake);//  w ww .ja v  a2 s  .c  o  m

    if (this.handler == null)
        this.handler = newhandler;

    // for Multiple Switches
    // handlerlist.add(handler);

    if (keyStore != null && keyStorePassword != null) {
        try {
            /* Set up factories and stores. */
            TrustManagerFactory tmFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            KeyStore tmpKS = null;
            tmFactory.init(tmpKS);

            /* Use keystore/pass defined in properties file. */
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(new FileInputStream(keyStore), keyStorePassword.toCharArray());

            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(ks, keyStorePassword.toCharArray());

            KeyManager[] km = kmf.getKeyManagers();
            TrustManager[] tm = tmFactory.getTrustManagers();

            /* Set up SSL prereqs for Netty. */
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(km, tm, null);
            SSLEngine sslEngine = sslContext.createSSLEngine();

            /* We are the server and we will create secure sessions. */
            sslEngine.setUseClientMode(false);
            sslEngine.setEnableSessionCreation(true);

            /* These are redundant (default), but for clarity... */
            sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
            sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());

            /*
             * First, decrypt w/handler+engine; then, proceed with rest of
             * handlers.
             */
            pipeline.addLast(PipelineHandler.SSL_TLS_ENCODER_DECODER, new SslHandler(sslEngine));
            log.info("SSL OpenFlow socket initialized and handler ready for switch.");
        } catch (Exception e) { /*
                                * There are lots of possible exceptions to
                                * catch, so this should get them all.
                                */
            log.error("Exception initializing SSL OpenFlow socket: {}", e.getMessage());
            throw e; /*
                      * If we wanted secure but didn't get it, we should
                      * bail.
                      */
        }
    }

    pipeline.addLast(PipelineHandler.OF_MESSAGE_DECODER, new OFMessageDecoder());
    pipeline.addLast(PipelineHandler.OF_MESSAGE_ENCODER, new OFMessageEncoder());
    pipeline.addLast(PipelineHandler.MAIN_IDLE,
            new IdleStateHandler(PipelineIdleReadTimeout.MAIN, PipelineIdleWriteTimeout.MAIN, 0));
    pipeline.addLast(PipelineHandler.READ_TIMEOUT, new ReadTimeoutHandler(30));
    pipeline.addLast(PipelineHandler.CHANNEL_HANDSHAKE_TIMEOUT,
            new HandshakeTimeoutHandler(newhandler, timer, PipelineHandshakeTimeout.CHANNEL));

    pipeline.addLast(PipelineHandler.CHANNEL_HANDLER, newhandler);
}

From source file:okhttp3.benchmarks.NettyHttpClient.java

License:Apache License

@Override
public void prepare(final Benchmark benchmark) {
    this.concurrencyLevel = benchmark.concurrencyLevel;
    this.targetBacklog = benchmark.targetBacklog;

    ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() {
        @Override//from   w  w  w  .  j  a v  a 2  s .c  o m
        public void initChannel(SocketChannel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();

            if (benchmark.tls) {
                SslClient sslClient = SslClient.localhost();
                SSLEngine engine = sslClient.sslContext.createSSLEngine();
                engine.setUseClientMode(true);
                pipeline.addLast("ssl", new SslHandler(engine));
            }

            pipeline.addLast("codec", new HttpClientCodec());
            pipeline.addLast("inflater", new HttpContentDecompressor());
            pipeline.addLast("handler", new HttpChannel(channel));
        }
    };

    bootstrap = new Bootstrap();
    bootstrap.group(new NioEventLoopGroup(concurrencyLevel))
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).channel(NioSocketChannel.class)
            .handler(channelInitializer);
}

From source file:org.apache.activemq.artemis.core.remoting.impl.netty.NettyAcceptor.java

License:Apache License

public synchronized void start() throws Exception {
    if (channelClazz != null) {
        // Already started
        return;/*w  w w  . jav  a 2s  .  c o m*/
    }

    if (useInvm) {
        channelClazz = LocalServerChannel.class;
        eventLoopGroup = new LocalEventLoopGroup();
    } else {
        int threadsToUse;

        if (nioRemotingThreads == -1) {
            // Default to number of cores * 3

            threadsToUse = Runtime.getRuntime().availableProcessors() * 3;
        } else {
            threadsToUse = this.nioRemotingThreads;
        }
        channelClazz = NioServerSocketChannel.class;
        eventLoopGroup = new NioEventLoopGroup(threadsToUse,
                new ActiveMQThreadFactory("activemq-netty-threads", true, getThisClassLoader()));
    }

    bootstrap = new ServerBootstrap();
    bootstrap.group(eventLoopGroup);
    bootstrap.channel(channelClazz);
    final SSLContext context;
    if (sslEnabled) {
        try {
            if (keyStorePath == null && TransportConstants.DEFAULT_TRUSTSTORE_PROVIDER.equals(keyStoreProvider))
                throw new IllegalArgumentException("If \"" + TransportConstants.SSL_ENABLED_PROP_NAME
                        + "\" is true then \"" + TransportConstants.KEYSTORE_PATH_PROP_NAME
                        + "\" must be non-null " + "unless an alternative \""
                        + TransportConstants.KEYSTORE_PROVIDER_PROP_NAME + "\" has been specified.");
            context = SSLSupport.createContext(keyStoreProvider, keyStorePath, keyStorePassword,
                    trustStoreProvider, trustStorePath, trustStorePassword);
        } catch (Exception e) {
            IllegalStateException ise = new IllegalStateException(
                    "Unable to create NettyAcceptor for " + host + ":" + port);
            ise.initCause(e);
            throw ise;
        }
    } else {
        context = null; // Unused
    }

    final AtomicBoolean warningPrinted = new AtomicBoolean(false);

    ChannelInitializer<Channel> factory = new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(Channel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            if (sslEnabled) {
                SSLEngine engine = context.createSSLEngine();

                engine.setUseClientMode(false);

                if (needClientAuth)
                    engine.setNeedClientAuth(true);

                // setting the enabled cipher suites resets the enabled protocols so we need
                // to save the enabled protocols so that after the customer cipher suite is enabled
                // we can reset the enabled protocols if a customer protocol isn't specified
                String[] originalProtocols = engine.getEnabledProtocols();

                if (enabledCipherSuites != null) {
                    try {
                        engine.setEnabledCipherSuites(
                                SSLSupport.parseCommaSeparatedListIntoArray(enabledCipherSuites));
                    } catch (IllegalArgumentException e) {
                        ActiveMQServerLogger.LOGGER.invalidCipherSuite(SSLSupport
                                .parseArrayIntoCommandSeparatedList(engine.getSupportedCipherSuites()));
                        throw e;
                    }
                }

                if (enabledProtocols != null) {
                    try {
                        engine.setEnabledProtocols(
                                SSLSupport.parseCommaSeparatedListIntoArray(enabledProtocols));
                    } catch (IllegalArgumentException e) {
                        ActiveMQServerLogger.LOGGER.invalidProtocol(
                                SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedProtocols()));
                        throw e;
                    }
                } else {
                    engine.setEnabledProtocols(originalProtocols);
                }

                // Strip "SSLv3" from the current enabled protocols to address the POODLE exploit.
                // This recommendation came from http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html
                String[] protocols = engine.getEnabledProtocols();
                Set<String> set = new HashSet<>();
                for (String s : protocols) {
                    if (s.equals("SSLv3") || s.equals("SSLv2Hello")) {
                        if (!warningPrinted.get()) {
                            ActiveMQServerLogger.LOGGER.disallowedProtocol(s);
                        }
                        continue;
                    }
                    set.add(s);
                }
                warningPrinted.set(true);
                engine.setEnabledProtocols(set.toArray(new String[0]));

                SslHandler handler = new SslHandler(engine);

                pipeline.addLast("ssl", handler);
            }
            pipeline.addLast(protocolHandler.getProtocolDecoder());
        }
    };
    bootstrap.childHandler(factory);

    // Bind
    bootstrap.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay);
    if (tcpReceiveBufferSize != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize);
    }
    if (tcpSendBufferSize != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
    }
    if (backlog != -1) {
        bootstrap.option(ChannelOption.SO_BACKLOG, backlog);
    }
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.childOption(ChannelOption.SO_REUSEADDR, true);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    channelGroup = new DefaultChannelGroup("activemq-accepted-channels", GlobalEventExecutor.INSTANCE);

    serverChannelGroup = new DefaultChannelGroup("activemq-acceptor-channels", GlobalEventExecutor.INSTANCE);

    if (httpUpgradeEnabled) {
        // the channel will be bound by the Web container and hand over after the HTTP Upgrade
        // handshake is successful
    } else {
        startServerChannels();

        paused = false;

        if (notificationService != null) {
            TypedProperties props = new TypedProperties();
            props.putSimpleStringProperty(new SimpleString("factory"),
                    new SimpleString(NettyAcceptorFactory.class.getName()));
            props.putSimpleStringProperty(new SimpleString("host"), new SimpleString(host));
            props.putIntProperty(new SimpleString("port"), port);
            Notification notification = new Notification(null, CoreNotificationType.ACCEPTOR_STARTED, props);
            notificationService.sendNotification(notification);
        }

        if (batchDelay > 0) {
            flusher = new BatchFlusher();

            batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, batchDelay, batchDelay,
                    TimeUnit.MILLISECONDS);
        }

        ActiveMQServerLogger.LOGGER.startedAcceptor(host, port, protocolsString);
    }
}