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:com.hxr.javatone.concurrency.netty.official.securechat.SecureChatClientInitializer.java

License:Apache License

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

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.

    SSLEngine engine = SecureChatSslContextFactory.getClientContext().createSSLEngine();
    engine.setUseClientMode(true);//ww  w .java 2 s  .c  o m

    pipeline.addLast("ssl", new SslHandler(engine));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast("decoder", new StringDecoder());
    pipeline.addLast("encoder", new StringEncoder());

    // and then business logic.
    pipeline.addLast("handler", new SecureChatClientHandler());
}

From source file:com.hxr.javatone.concurrency.netty.official.securechat.SecureChatServerInitializer.java

License:Apache License

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

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    ///*from w  w  w  .j a  va 2  s. c  om*/
    // Read SecureChatSslContextFactory
    // if you need client certificate authentication.

    SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine();
    engine.setUseClientMode(false);

    pipeline.addLast("ssl", new SslHandler(engine));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast("decoder", new StringDecoder());
    pipeline.addLast("encoder", new StringEncoder());

    // and then business logic.
    pipeline.addLast("handler", new SecureChatServerHandler());
}

From source file:com.ibm.mqlight.api.impl.network.NettyNetworkService.java

License:Apache License

@Override
public void connect(Endpoint endpoint, NetworkListener listener, Promise<NetworkChannel> promise) {
    final String methodName = "connect";
    logger.entry(this, methodName, endpoint, listener, promise);

    SslContext sslCtx = null;/*www.j av a2  s .  c  o m*/
    try {
        if (endpoint.getCertChainFile() != null && endpoint.getCertChainFile().exists()) {
            try (FileInputStream fileInputStream = new FileInputStream(endpoint.getCertChainFile())) {
                KeyStore jks = KeyStore.getInstance("JKS");
                jks.load(fileInputStream, null);
                TrustManagerFactory trustManagerFactory = TrustManagerFactory
                        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                trustManagerFactory.init(jks);
                sslCtx = SslContext.newClientContext();
                if (sslCtx instanceof JdkSslContext) {
                    ((JdkSslContext) sslCtx).context().init(null, trustManagerFactory.getTrustManagers(), null);
                }
            } catch (IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException
                    | KeyManagementException e) {
                logger.data(this, methodName, e.toString());
            }
        }
        // fallback to passing as .PEM file (or null, which loads default cacerts)
        if (sslCtx == null) {
            sslCtx = SslContext.newClientContext(endpoint.getCertChainFile());
        }

        final SSLEngine sslEngine = sslCtx.newEngine(null, endpoint.getHost(), endpoint.getPort());
        sslEngine.setUseClientMode(true);

        final LinkedList<String> enabledProtocols = new LinkedList<String>() {
            private static final long serialVersionUID = 7838479468739671083L;
            {
                for (String protocol : sslEngine.getSupportedProtocols()) {
                    if (!disabledProtocolPattern.matcher(protocol).matches()) {
                        add(protocol);
                    }
                }
            }
        };
        sslEngine.setEnabledProtocols(enabledProtocols.toArray(new String[0]));
        logger.data(this, methodName, "enabledProtocols", Arrays.toString(sslEngine.getEnabledProtocols()));

        final LinkedList<String> enabledCipherSuites = new LinkedList<String>() {
            private static final long serialVersionUID = 7838479468739671083L;
            {
                for (String cipher : sslEngine.getSupportedCipherSuites()) {
                    if (!disabledCipherPattern.matcher(cipher).matches()) {
                        add(cipher);
                    }
                }
            }
        };
        sslEngine.setEnabledCipherSuites(enabledCipherSuites.toArray(new String[0]));
        logger.data(this, methodName, "enabledCipherSuites",
                Arrays.toString(sslEngine.getEnabledCipherSuites()));

        if (endpoint.getVerifyName()) {
            SSLParameters sslParams = sslEngine.getSSLParameters();
            sslParams.setEndpointIdentificationAlgorithm("HTTPS");
            sslEngine.setSSLParameters(sslParams);
        }

        // The listener must be added to the ChannelFuture before the bootstrap channel initialisation completes (i.e.
        // before the NettyInboundHandler is added to the channel pipeline) otherwise the listener may not be able to 
        // see the NettyInboundHandler, when its operationComplete() method is called (there is a small window where
        // the socket connection fails just after initChannel has complete but before ConnectListener is added, with
        // the ConnectListener.operationComplete() being called as though the connection was successful)
        // Hence we synchronise here and within the ChannelInitializer.initChannel() method.
        synchronized (bootstrapSync) {
            final ChannelHandler handler;
            if (endpoint.useSsl()) {
                handler = new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        synchronized (bootstrapSync) {
                            ch.pipeline().addFirst(new SslHandler(sslEngine));
                            ch.pipeline().addLast(new NettyInboundHandler(ch));
                        }
                    }
                };
            } else {
                handler = new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        synchronized (bootstrapSync) {
                            ch.pipeline().addLast(new NettyInboundHandler(ch));
                        }
                    }
                };
            }
            final Bootstrap bootstrap = getBootstrap(endpoint.useSsl(), sslEngine, handler);
            final ChannelFuture f = bootstrap.connect(endpoint.getHost(), endpoint.getPort());
            f.addListener(new ConnectListener(endpoint, f, promise, listener));
        }

    } catch (SSLException e) {
        if (e.getCause() == null) {
            promise.setFailure(new SecurityException(e.getMessage(), e));
        } else {
            promise.setFailure(new SecurityException(e.getCause().getMessage(), e.getCause()));
        }
    }

    logger.exit(this, methodName);
}

From source file:com.king.platform.net.http.netty.SslInitializer.java

License:Apache License

public SslHandler createSslHandler(String peerHost, int peerPort) throws IOException, GeneralSecurityException {
    SSLEngine sslEngine = sslFactory.newSSLEngine(peerHost, peerPort);
    SslHandler sslHandler = new SslHandler(sslEngine);
    if (handshakeTimeout > 0) {
        sslHandler.setHandshakeTimeoutMillis(handshakeTimeout);
    }//from   w w w  .j  a v a2  s. co m
    return sslHandler;
}

From source file:com.kingmed.bidir.gateway.server.GatewayServerInitializer.java

License:Apache License

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    SSLEngine engine = null;/*www .ja  v a2  s  .  c om*/
    if (SSLMODE.CA.toString().equals(tlsMode)) {
        engine = GatewaySslContextFactory
                .getServerContext(tlsMode,
                        System.getProperty("user.dir")
                                + "/src/main/java/com/kingmed/bidir/gateway/conf/sGateway.jks",
                        null)
                .createSSLEngine();
    } else if (SSLMODE.CSA.toString().equals(tlsMode)) {
        engine = GatewaySslContextFactory.getClientContext(tlsMode,
                System.getProperty("user.dir") + "/src/main/java/com/kingmed/bidir/gateway/conf/sGateway.jks",
                System.getProperty("user.dir") + "/src/main/java/com/kingmed/bidir/gateway/conf/sGateway.jks")
                .createSSLEngine();
    } else {
        System.err.println("ERROR: " + tlsMode);
        System.exit(-1);
    }
    engine.setUseClientMode(false);

    if (SSLMODE.CSA.toString().equals(tlsMode))
        engine.setUseClientMode(true);

    pipeline.addLast("ssl", new SslHandler(engine));

    pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8 * 1024, Delimiters.lineDelimiter()));
    pipeline.addLast("decoder", new StringDecoder());
    pipeline.addLast("encoder", new StringEncoder());

    pipeline.addLast("handler", new GatewayServerHandler());
}

From source file:com.linkedin.mitm.proxy.channel.ChannelMediator.java

License:Open Source License

/**
 * Create {@link io.netty.handler.ssl.SslHandler} and send TCP handshaking using
 * {@link javax.net.ssl.SSLEngine}//  w  w w.j  av  a2s  .  c o m
 * After add ssl handler to the end of {@link io.netty.channel.ChannelPipeline}, it enable
 * secure communications over SSL/TLS
 *
 * @param isSslClient true if the channel start handshaking or false if accept handshaking
 * @param channel the channel to start handshaking
 * */
private Future<Channel> handshake(SSLEngine sslEngine, boolean isSslClient, Channel channel) {
    sslEngine.setUseClientMode(isSslClient);
    if (channel != null) {
        channel.config().setAutoRead(true);
    }
    SslHandler handler = new SslHandler(sslEngine);
    channel.pipeline().addFirst("ssl", handler);
    LOG.debug("About to start handshaking...");
    return handler.handshakeFuture();
}

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

License:Apache License

public SslRequestHandler(SSLContext sslContext, SSLParameters sslParameters) {
    if (sslContext == null) {
        _sslHandler = null;/*w w w .ja va 2 s. c o m*/
    } else {
        SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(true);
        if (sslParameters != null) {
            String[] cipherSuites = sslParameters.getCipherSuites();
            if (cipherSuites != null && cipherSuites.length > 0) {
                sslEngine.setEnabledCipherSuites(sslParameters.getCipherSuites());
            }
            String[] protocols = sslParameters.getProtocols();
            if (protocols != null && protocols.length > 0) {
                sslEngine.setEnabledProtocols(sslParameters.getProtocols());
            }
        }
        _sslHandler = new SslHandler(sslEngine);
    }
}

From source file:com.ltln.modules.openflow.controller.manager.OFChannelInitializer.java

License:Apache License

@Override
protected void initChannel(Channel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    OFChannelHandler handler = new OFChannelHandler(switchManager, connectionListener, pipeline, timer,
            ofBitmaps, defaultFactory);//from   ww w  .j  a  v a  2s . com

    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(handler, timer, PipelineHandshakeTimeout.CHANNEL));

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

From source file:com.netiq.websockify.PortUnificationHandler.java

License:Apache License

private void enableSsl(ChannelHandlerContext ctx) {
    ChannelPipeline p = ctx.getPipeline();

    Logger.getLogger(PortUnificationHandler.class.getName())
            .fine("SSL request from " + ctx.getChannel().getRemoteAddress() + ".");

    SSLEngine engine = WebsockifySslContext.getInstance(keystore, keystorePassword).getServerContext()
            .createSSLEngine();//from w  w w  . jav  a  2s.  c o  m
    engine.setUseClientMode(false);

    p.addLast("ssl", new SslHandler(engine));
    p.addLast("unificationA", new PortUnificationHandler(cf, resolver, SSLSetting.OFF, keystore,
            keystorePassword, webDirectory, ctx));
    p.remove(this);
}

From source file:com.ning.http.client.providers.netty_4.NettyAsyncHttpProvider.java

License:Apache License

void constructSSLPipeline(final NettyConnectListener<?> cl) {

    secureBootstrap.handler(new ChannelInitializer() {
        /* @Override */
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();

            try {
                pipeline.addLast(SSL_HANDLER, new SslHandler(createSSLEngine()));
            } catch (Throwable ex) {
                abort(cl.future(), ex);/*w w  w .  j  a v  a2s.  co m*/
            }

            pipeline.addLast(HTTP_HANDLER, newHttpClientCodec());

            if (config.isCompressionEnabled()) {
                pipeline.addLast("inflater", new HttpContentDecompressor());
            }
            pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
            pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
        }
    });

    secureWebSocketBootstrap.handler(new ChannelInitializer() {

        /* @Override */
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();

            try {
                pipeline.addLast(SSL_HANDLER, new SslHandler(createSSLEngine()));
            } catch (Throwable ex) {
                abort(cl.future(), ex);
            }

            pipeline.addLast("ws-decoder", new HttpResponseDecoder());
            pipeline.addLast("ws-encoder", new HttpRequestEncoder());
            pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
        }
    });
}