Example usage for javax.net.ssl SSLEngine setNeedClientAuth

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

Introduction

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

Prototype

public abstract void setNeedClientAuth(boolean need);

Source Link

Document

Configures the engine to require client authentication.

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.
 *///from w w w.  j a  v a2s  .co 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:com.eucalyptus.crypto.util.SslSetup.java

public static SSLEngine getServerEngine() {//TODO:GRZE: @Configurability
    final SSLEngine engine = SERVER_CONTEXT.createSSLEngine();
    engine.setUseClientMode(false);//from  w  ww .j ava  2s .  c  o m
    engine.setWantClientAuth(false);
    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);/*  w w w  .  j a v  a  2 s . c om*/
    engine.setNeedClientAuth(false);

    return engine;
}

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

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

    engine.setUseClientMode(false);//from   ww w.j  a  va 2  s .  c om
    engine.setNeedClientAuth(false);
    engine.setEnableSessionCreation(true);

    return engine;
}

From source file:org.siddhiesb.transport.http.conn.ServerSSLSetupHandler.java

public void initalize(final SSLEngine sslengine) throws SSLException {
    if (clientAuth != null) {
        switch (clientAuth) {
        case OPTIONAL:
            sslengine.setWantClientAuth(true);
            break;
        case REQUIRED:
            sslengine.setNeedClientAuth(true);
        }//from  w  w w.  jav  a2s  .c o  m
    }
    // set handshake protocols if they are specified in transport
    // configuration.
    if (httpsProtocols != null) {
        sslengine.setEnabledProtocols(httpsProtocols);
    }

}

From source file:org.apache.axis2.transport.nhttp.HttpCoreNIOSSLListener.java

/**
 * Create the SSLIOSessionHandler to initialize the SSL session / engine, and request for
 * client authentication at the following levels, through an Axis2 transport configuration
 * parameter as follows:// ww w . j  a  va2 s . c om
 * SSLVerifyClient - none, optional, require
 *
 * @param transportIn the Axis2 transport configuration
 * @return the SSLIOSessionHandler to be used
 * @throws AxisFault if a configuration error occurs
 */
protected SSLIOSessionHandler getSSLIOSessionHandler(TransportInDescription transportIn) throws AxisFault {

    final Parameter clientAuth = transportIn.getParameter("SSLVerifyClient");

    return new SSLIOSessionHandler() {

        public void initalize(SSLEngine sslengine, HttpParams params) {
            if (clientAuth != null) {
                if ("optional".equals(clientAuth.getValue())) {
                    sslengine.setWantClientAuth(true);
                } else if ("require".equals(clientAuth.getValue())) {
                    sslengine.setNeedClientAuth(true);
                }
            }
        }

        public void verify(SocketAddress removeAddress, SSLSession session) throws SSLException {
        }
    };
}

From source file:org.apache.hadoop.security.ssl.SSLFactory.java

/**
 * Returns a configured SSLEngine.//from w  w w  .  j a v  a 2 s  .c  o m
 *
 * @return the configured SSLEngine.
 * @throws GeneralSecurityException thrown if the SSL engine could not
 * be initialized.
 * @throws IOException thrown if and IO error occurred while loading
 * the server keystore.
 */
public SSLEngine createSSLEngine() throws GeneralSecurityException, IOException {
    SSLEngine sslEngine = context.createSSLEngine();
    if (mode == Mode.CLIENT) {
        sslEngine.setUseClientMode(true);
    } else {
        sslEngine.setUseClientMode(false);
        sslEngine.setNeedClientAuth(requireClientCert);
        disableExcludedCiphers(sslEngine);
    }
    sslEngine.setEnabledProtocols(enabledProtocols);
    return sslEngine;
}

From source file:org.apache.nifi.processor.util.listen.dispatcher.SocketChannelDispatcher.java

@Override
public void run() {
    while (!stopped) {
        try {/*from  ww  w  . j a  va2s .  c om*/
            int selected = selector.select();
            // if stopped the selector could already be closed which would result in a ClosedSelectorException
            if (selected > 0 && !stopped) {
                Iterator<SelectionKey> selectorKeys = selector.selectedKeys().iterator();
                // if stopped we don't want to modify the keys because close() may still be in progress
                while (selectorKeys.hasNext() && !stopped) {
                    SelectionKey key = selectorKeys.next();
                    selectorKeys.remove();
                    if (!key.isValid()) {
                        continue;
                    }
                    if (key.isAcceptable()) {
                        // Handle new connections coming in
                        final ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                        final SocketChannel socketChannel = channel.accept();
                        // Check for available connections
                        if (currentConnections.incrementAndGet() > maxConnections) {
                            currentConnections.decrementAndGet();
                            logger.warn("Rejecting connection from {} because max connections has been met",
                                    new Object[] { socketChannel.getRemoteAddress().toString() });
                            IOUtils.closeQuietly(socketChannel);
                            continue;
                        }
                        logger.debug("Accepted incoming connection from {}",
                                new Object[] { socketChannel.getRemoteAddress().toString() });
                        // Set socket to non-blocking, and register with selector
                        socketChannel.configureBlocking(false);
                        SelectionKey readKey = socketChannel.register(selector, SelectionKey.OP_READ);

                        // Prepare the byte buffer for the reads, clear it out
                        ByteBuffer buffer = bufferPool.poll();
                        buffer.clear();
                        buffer.mark();

                        // If we have an SSLContext then create an SSLEngine for the channel
                        SSLSocketChannel sslSocketChannel = null;
                        if (sslContext != null) {
                            final SSLEngine sslEngine = sslContext.createSSLEngine();
                            sslEngine.setUseClientMode(false);

                            switch (clientAuth) {
                            case REQUIRED:
                                sslEngine.setNeedClientAuth(true);
                                break;
                            case WANT:
                                sslEngine.setWantClientAuth(true);
                                break;
                            case NONE:
                                sslEngine.setNeedClientAuth(false);
                                sslEngine.setWantClientAuth(false);
                                break;
                            }

                            sslSocketChannel = new SSLSocketChannel(sslEngine, socketChannel);
                        }

                        // Attach the buffer and SSLSocketChannel to the key
                        SocketChannelAttachment attachment = new SocketChannelAttachment(buffer,
                                sslSocketChannel);
                        readKey.attach(attachment);
                    } else if (key.isReadable()) {
                        // Clear out the operations the select is interested in until done reading
                        key.interestOps(0);
                        // Create a handler based on the protocol and whether an SSLEngine was provided or not
                        final Runnable handler;
                        if (sslContext != null) {
                            handler = handlerFactory.createSSLHandler(key, this, charset, eventFactory, events,
                                    logger);
                        } else {
                            handler = handlerFactory.createHandler(key, this, charset, eventFactory, events,
                                    logger);
                        }

                        // run the handler
                        executor.execute(handler);
                    }
                }
            }
            // Add back all idle sockets to the select
            SelectionKey key;
            while ((key = keyQueue.poll()) != null) {
                key.interestOps(SelectionKey.OP_READ);
            }
        } catch (IOException e) {
            logger.error("Error accepting connection from SocketChannel", e);
        }
    }
}

From source file:org.apache.synapse.transport.nhttp.HttpCoreNIOSSLListener.java

/**
 * Create the SSLIOSessionHandler to initialize the SSL session / engine, and request for
 * client authentication at the following levels, through an Axis2 transport configuration
 * parameter as follows://from w w  w  .  java 2  s  .co m
 * SSLVerifyClient - none, optional, require
 *
 * @param transportIn the Axis2 transport configuration
 * @return the SSLIOSessionHandler to be used
 * @throws AxisFault if a configuration error occurs
 */
protected SSLSetupHandler getSSLIOSessionHandler(TransportInDescription transportIn) throws AxisFault {

    final Parameter clientAuth = transportIn.getParameter("SSLVerifyClient");

    return new SSLSetupHandler() {

        public void initalize(SSLEngine sslengine) {
            if (clientAuth != null) {
                if ("optional".equals(clientAuth.getValue())) {
                    sslengine.setWantClientAuth(true);
                } else if ("require".equals(clientAuth.getValue())) {
                    sslengine.setNeedClientAuth(true);
                }
            }
        }

        public void verify(IOSession ioSession, SSLSession sslSession) throws SSLException {

        }
    };
}

From source file:org.jenkinsci.remoting.protocol.impl.SSLEngineFilterLayerTest.java

@Theory
public void smokes(NetworkLayerFactory serverFactory, NetworkLayerFactory clientFactory) throws Exception {
    SSLEngine serverEngine = serverCtx.createSSLEngine();
    serverEngine.setUseClientMode(false);
    serverEngine.setNeedClientAuth(true);
    SSLEngine clientEngine = clientCtx.createSSLEngine();
    clientEngine.setUseClientMode(true);

    ProtocolStack<IOBufferMatcher> client = ProtocolStack
            .on(clientFactory.create(selector.hub(), serverToClient.source(), clientToServer.sink()))
            .filter(new SSLEngineFilterLayer(clientEngine, null)).build(new IOBufferMatcherLayer());

    ProtocolStack<IOBufferMatcher> server = ProtocolStack
            .on(serverFactory.create(selector.hub(), clientToServer.source(), serverToClient.sink()))
            .filter(new SSLEngineFilterLayer(serverEngine, null)).build(new IOBufferMatcherLayer());

    byte[] expected = "Here is some sample data".getBytes("UTF-8");
    ByteBuffer data = ByteBuffer.allocate(expected.length);
    data.put(expected);//from  w  ww  . j  a  va  2  s  .  c o m
    data.flip();
    server.get().send(data);
    client.get().awaitByteContent(is(expected));
    assertThat(client.get().asByteArray(), is(expected));
    server.get().close();
    client.get().awaitClose();
}