Example usage for javax.net.ssl SSLEngine setUseClientMode

List of usage examples for javax.net.ssl SSLEngine setUseClientMode

Introduction

In this page you can find the example usage for javax.net.ssl SSLEngine setUseClientMode.

Prototype

public abstract void setUseClientMode(boolean mode);

Source Link

Document

Configures the engine to use client (or server) mode when handshaking.

Usage

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

/**
 * OVSDB Passive listening thread that uses Netty ServerBootstrap to open
 * passive connection with Ssl and handle channel callbacks.
 *//*w w  w  . ja  va  2  s  .  com*/
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:com.eucalyptus.crypto.util.SslSetup.java

public static SSLEngine getServerEngine() {//TODO:GRZE: @Configurability
    final SSLEngine engine = SERVER_CONTEXT.createSSLEngine();
    engine.setUseClientMode(false);
    engine.setWantClientAuth(false);/*w  w w  .ja  v  a  2s . c  o m*/
    engine.setNeedClientAuth(false);
    engine.setEnabledProtocols(
            SslUtils.getEnabledProtocols(SERVER_SSL_PROTOCOLS, engine.getSupportedProtocols()));
    engine.setEnabledCipherSuites(
            SslUtils.getEnabledCipherSuites(SERVER_SSL_CIPHERS, SERVER_SUPPORTED_CIPHERS));
    return engine;
}

From source file:com.github.mrstampy.gameboot.otp.netty.client.EncryptedClientInitializer.java

private SSLEngine createSslEngine() {
    SSLEngine engine = sslContext.createSSLEngine();

    engine.setUseClientMode(true);
    engine.setNeedClientAuth(false);//  w  ww  . j ava  2 s . c  om

    return engine;
}

From source file:com.github.mrstampy.gameboot.otp.netty.server.EncryptedServerInitializer.java

private SSLEngine createSslEngine() {
    SSLEngine engine = sslContext.createSSLEngine();

    engine.setUseClientMode(false);
    engine.setNeedClientAuth(false);//from  w  w  w  .  j av  a 2s . c o m
    engine.setEnableSessionCreation(true);

    return engine;
}

From source file:com.hs.mail.imap.server.ImapServer.java

private ChannelPipelineFactory createPipelineFactory() {

    return new ChannelPipelineFactory() {

        public ChannelPipeline getPipeline() throws Exception {
            // Create a default pipeline implementation.
            ChannelPipeline pipeline = Channels.pipeline();

            if (isUseTLS()) {
                SSLEngine engine = Config.getSSLContext().createSSLEngine();
                engine.setUseClientMode(false);
                pipeline.addFirst("ssl", new SslHandler(engine));
            }//from  ww  w. j  av a2s. c o  m
            if (Config.getBooleanProperty("imap_trace_protocol", false)) {
                pipeline.addLast("debug", createDebuggingHandler());
            }
            pipeline.addLast("timeout", timeoutHandler);
            int maxLineLength = (int) Config.getNumberProperty("imap_line_limit", 8192);
            pipeline.addLast("decoder", new ImapRequestDecoder(maxLineLength));
            pipeline.addLast("encoder", new ImapMessageEncoder());

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

            return pipeline;
        }

    };
}

From source file:org.maodian.flyingcat.xmpp.state.DefaultElementVisitor.java

@Override
public State handleTLS(XmppContext xmppCtx, TLS tls) throws XMLStreamException {
    ChannelHandlerContext ctx = xmppCtx.getNettyChannelHandlerContext();
    SSLEngine engine = SecureSslContextFactory.getServerContext().createSSLEngine();
    engine.setUseClientMode(false);
    SslHandler sslHandler = new SslHandler(engine, true);
    sslHandler.sslCloseFuture().addListener(new ChannelFutureListener() {

        @Override/*from ww  w  .  j a  va2 s  . c o m*/
        public void operationComplete(ChannelFuture future) throws Exception {
            log.info("Close the socket since SSL connection has been closed by client");
            future.channel().close();
        }
    });
    ctx.pipeline().addFirst("ssl", sslHandler);

    StringWriter writer = new StringWriter();
    XMLStreamWriter xmlsw = XMLOutputFactoryHolder.getXMLOutputFactory().createXMLStreamWriter(writer);
    xmlsw.writeEmptyElement("", "proceed", XmppNamespace.TLS);
    xmlsw.setPrefix("", XmppNamespace.TLS);
    xmlsw.writeNamespace("", XmppNamespace.TLS);
    xmlsw.writeEndDocument();
    xmppCtx.flush(writer.toString());
    return xmppCtx.getGlobalContext().getTlsStreamState();
}

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

@Override
public OvsdbClient connectWithSsl(final InetAddress address, final int port, final SSLContext sslContext) {
    try {// ww  w  .  j a  va2  s  .co  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:mitm.BouncyCastleSslEngineSource.java

@Override
public SSLEngine newSslEngine(String remoteHost, int remotePort) {
    SSLEngine sslEngine = sslContext.createSSLEngine(remoteHost, remotePort);
    sslEngine.setUseClientMode(true);
    if (!tryHostNameVerificationJava7(sslEngine) && !tryHostNameVerificationJava6(sslEngine)) {
        LOG.debug("Host Name Verification is not supported, causes insecure HTTPS connection");
    }//w ww .  j  av a 2 s. com
    filterWeakCipherSuites(sslEngine);
    return sslEngine;
}

From source file:io.dyn.net.tcp.TcpServer.java

@SuppressWarnings({ "unchecked" })
@Override//from   www  .j a  v a2 s.c o m
public T start() {
    Tasks.execute(new Runnable() {
        @Override
        public void run() {
            if (!started.get()) {
                on(Lifecycle.STOP, new CompletionHandler() {
                    @Override
                    protected void complete() {
                        channel.close();
                        started.set(false);
                    }
                });
                bootstrap.setOption("backlog", backlog);
                bootstrap.setOption("child.keepAlive", keepAlive);
                bootstrap.setOption("child.reuseAddress", reuseAddress);
                bootstrap.setOption("child.receiveBufferSize", Buffer.SMALL_BUFFER_SIZE);
                bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
                    @Override
                    public ChannelPipeline getPipeline() throws Exception {
                        final ChannelPipeline pipeline = Channels.pipeline();
                        if (ssl) {
                            SSLEngine engine;
                            try {
                                engine = SSL.sslContext(sslConfig).createSSLEngine();
                                engine.setUseClientMode(false);
                                pipeline.addLast("ssl", new SslHandler(engine));
                            } catch (Exception e) {
                                event(Events.classToEventExpression(e.getClass()), e);
                            }
                        }
                        pipeline.addLast("channelHandler", new SimpleChannelUpstreamHandler() {
                            @Override
                            public void channelConnected(final ChannelHandlerContext ctx, ChannelStateEvent e)
                                    throws Exception {
                                log.debug("channel connected: " + ctx.getChannel());
                                Tasks.currentExecutor(new TaskExecutor() {
                                    @Override
                                    public void execute(Runnable task) {
                                        ctx.getPipeline().execute(task);
                                    }
                                });

                                Dyn<Channel> dyn = Dyn.wrap(ctx.getChannel());
                                ctx.getChannel().setAttachment(dyn);
                                event(NioEvents.CONNECTED, dyn);
                            }

                            @Override
                            public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e)
                                    throws Exception {
                                log.debug("channel disconnected: " + ctx.getChannel());
                                Tasks.currentExecutor(null);
                                event(NioEvents.DISCONNECTED, ctx.getChannel().getAttachment());
                            }

                            @Override
                            public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
                                    throws Exception {
                                event(Events.classToEventExpression(e.getCause().getClass()), e.getCause());
                            }
                        });
                        if (null != protocolHandler) {
                            pipeline.addLast("protocol", new SimpleChannelUpstreamHandler() {
                                Protocol protocol = TcpServer.this.protocolHandler().newInstance();

                                @Override
                                public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
                                        throws Exception {
                                    if (e.getMessage() instanceof ChannelBuffer) {
                                        ChannelBuffer cb = (ChannelBuffer) e.getMessage();
                                        int available = cb.readableBytes();
                                        byte[] bs = new byte[available];
                                        cb.readBytes(bs);
                                        protocol.decode(Buffer.wrap(bs),
                                                (Evented) ctx.getChannel().getAttachment());
                                    }
                                }
                            });
                        }
                        configurePipeline(pipeline);
                        return pipeline;
                    }
                });

                try {
                    channel = bootstrap.bind(new InetSocketAddress(InetAddress.getByName(host), port));
                    started.set(true);
                    //LOG.info("Listening on port %s...", port);
                    event(Lifecycle.START);
                } catch (UnknownHostException e) {
                    event(Events.classToEventExpression(e.getClass()), e);
                }
            }
        }
    }, executor);
    return (T) this;
}

From source file:com.hypersocket.server.HypersocketServerImpl.java

public SSLEngine createSSLEngine(InetSocketAddress localAddress, InetSocketAddress remoteAddress) {

    SSLEngine engine = getSSLContext(localAddress, remoteAddress).createSSLEngine();

    engine.setUseClientMode(false);
    engine.setWantClientAuth(false);// w ww  . j  a va  2 s  .  c o  m

    if (enabledCipherSuites != null && enabledCipherSuites.length > 0) {
        engine.setEnabledCipherSuites(enabledCipherSuites);
    }
    if (enabledProtocols != null && enabledProtocols.length > 0) {
        engine.setEnabledProtocols(enabledProtocols);
    }
    return engine;

}