Search in sources :

Example 71 with SSLEngine

use of javax.net.ssl.SSLEngine in project qpid-broker-j by apache.

the class NonBlockingConnectionTLSDelegate method createSSLEngine.

private SSLEngine createSSLEngine(AmqpPort<?> port) {
    SSLEngine sslEngine = port.getSSLContext().createSSLEngine();
    sslEngine.setUseClientMode(false);
    SSLUtil.updateEnabledTlsProtocols(sslEngine, port.getTlsProtocolWhiteList(), port.getTlsProtocolBlackList());
    SSLUtil.updateEnabledCipherSuites(sslEngine, port.getTlsCipherSuiteWhiteList(), port.getTlsCipherSuiteBlackList());
    if (port.getTlsCipherSuiteWhiteList() != null && !port.getTlsCipherSuiteWhiteList().isEmpty()) {
        SSLParameters sslParameters = sslEngine.getSSLParameters();
        sslParameters.setUseCipherSuitesOrder(true);
        sslEngine.setSSLParameters(sslParameters);
    }
    if (port.getNeedClientAuth()) {
        sslEngine.setNeedClientAuth(true);
    } else if (port.getWantClientAuth()) {
        sslEngine.setWantClientAuth(true);
    }
    return sslEngine;
}
Also used : SSLParameters(javax.net.ssl.SSLParameters) SSLEngine(javax.net.ssl.SSLEngine)

Example 72 with SSLEngine

use of javax.net.ssl.SSLEngine in project ambry by linkedin.

the class PublicAccessLogHandlerTest method createChannel.

// helpers
// general
/**
 * Creates an {@link EmbeddedChannel} that incorporates an instance of {@link PublicAccessLogHandler}
 * and {@link EchoMethodHandler}.
 * @param useSSL {@code true} to add an {@link SslHandler} to the pipeline.
 * @return an {@link EmbeddedChannel} that incorporates an instance of {@link PublicAccessLogHandler}
 *         and {@link EchoMethodHandler}, and an {@link SslHandler} if needed.
 */
private EmbeddedChannel createChannel(boolean useSSL) {
    EmbeddedChannel channel = new EmbeddedChannel();
    if (useSSL) {
        SSLEngine sslEngine = SSL_CONTEXT.newEngine(channel.alloc());
        // HttpRequests pass through the SslHandler without a handshake (it only operates on ByteBuffers) so we have
        // to mock certain methods of SSLEngine and SSLSession to ensure that we can test certificate logging.
        SSLEngine mockSSLEngine = new MockSSLEngine(sslEngine, new MockSSLSession(sslEngine.getSession(), new Certificate[] { PEER_CERT }));
        channel.pipeline().addLast(new SslHandler(mockSSLEngine));
    }
    channel.pipeline().addLast(new PublicAccessLogHandler(publicAccessLogger, new NettyMetrics(new MetricRegistry()))).addLast(new EchoMethodHandler());
    return channel;
}
Also used : SSLEngine(javax.net.ssl.SSLEngine) MetricRegistry(com.codahale.metrics.MetricRegistry) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) SslHandler(io.netty.handler.ssl.SslHandler) X509Certificate(java.security.cert.X509Certificate) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) Certificate(java.security.cert.Certificate)

Example 73 with SSLEngine

use of javax.net.ssl.SSLEngine in project nifi by apache.

the class SocketChannelDispatcher method run.

@Override
public void run() {
    while (!stopped) {
        try {
            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);
        }
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) SocketChannel(java.nio.channels.SocketChannel) SSLSocketChannel(org.apache.nifi.remote.io.socket.ssl.SSLSocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SSLSocketChannel(org.apache.nifi.remote.io.socket.ssl.SSLSocketChannel) SSLEngine(javax.net.ssl.SSLEngine) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) ServerSocketChannel(java.nio.channels.ServerSocketChannel)

Example 74 with SSLEngine

use of javax.net.ssl.SSLEngine in project nifi by apache.

the class SocketChannelRecordReaderDispatcher method run.

@Override
public void run() {
    while (!stopped) {
        try {
            final SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel == null) {
                Thread.sleep(20);
                continue;
            }
            final SocketAddress remoteSocketAddress = socketChannel.getRemoteAddress();
            socketChannel.socket().setSoTimeout(socketReadTimeout);
            socketChannel.socket().setReceiveBufferSize(receiveBufferSize);
            if (currentConnections.incrementAndGet() > maxConnections) {
                currentConnections.decrementAndGet();
                final String remoteAddress = remoteSocketAddress == null ? "null" : remoteSocketAddress.toString();
                logger.warn("Rejecting connection from {} because max connections has been met", new Object[] { remoteAddress });
                IOUtils.closeQuietly(socketChannel);
                continue;
            }
            if (logger.isDebugEnabled()) {
                final String remoteAddress = remoteSocketAddress == null ? "null" : remoteSocketAddress.toString();
                logger.debug("Accepted connection from {}", new Object[] { remoteAddress });
            }
            // create a StandardSocketChannelRecordReader or an SSLSocketChannelRecordReader based on presence of SSLContext
            final SocketChannelRecordReader socketChannelRecordReader;
            if (sslContext == null) {
                socketChannelRecordReader = new StandardSocketChannelRecordReader(socketChannel, readerFactory, this);
            } else {
                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;
                }
                final SSLSocketChannel sslSocketChannel = new SSLSocketChannel(sslEngine, socketChannel);
                socketChannelRecordReader = new SSLSocketChannelRecordReader(socketChannel, sslSocketChannel, readerFactory, this);
            }
            // queue the SocketChannelRecordReader for processing by the processor
            recordReaders.offer(socketChannelRecordReader);
        } catch (Exception e) {
            logger.error("Error dispatching connection: " + e.getMessage(), e);
        }
    }
}
Also used : SSLSocketChannel(org.apache.nifi.remote.io.socket.ssl.SSLSocketChannel) SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SSLSocketChannel(org.apache.nifi.remote.io.socket.ssl.SSLSocketChannel) SSLEngine(javax.net.ssl.SSLEngine) SocketAddress(java.net.SocketAddress)

Example 75 with SSLEngine

use of javax.net.ssl.SSLEngine in project async-http-client by AsyncHttpClient.

the class JsseSslEngineFactory method newSslEngine.

@Override
public SSLEngine newSslEngine(AsyncHttpClientConfig config, String peerHost, int peerPort) {
    SSLEngine sslEngine = sslContext.createSSLEngine(domain(peerHost), peerPort);
    configureSslEngine(sslEngine, config);
    return sslEngine;
}
Also used : SSLEngine(javax.net.ssl.SSLEngine)

Aggregations

SSLEngine (javax.net.ssl.SSLEngine)494 IOException (java.io.IOException)97 SSLContext (javax.net.ssl.SSLContext)97 ByteBuffer (java.nio.ByteBuffer)91 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)75 SSLException (javax.net.ssl.SSLException)71 Test (org.junit.Test)64 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)54 SslHandler (io.netty.handler.ssl.SslHandler)52 SSLEngineResult (javax.net.ssl.SSLEngineResult)50 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)47 MethodSource (org.junit.jupiter.params.provider.MethodSource)44 SSLParameters (javax.net.ssl.SSLParameters)43 InetSocketAddress (java.net.InetSocketAddress)42 KeyManagementException (java.security.KeyManagementException)42 ReadOnlyBufferException (java.nio.ReadOnlyBufferException)35 KeyStore (java.security.KeyStore)28 Test (org.junit.jupiter.api.Test)22 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)21 Socket (java.net.Socket)21