Search in sources :

Example 81 with SSLParameters

use of javax.net.ssl.SSLParameters in project pravega by pravega.

the class TcpClientConnection method createClientSocket.

/**
 * Creates a socket connected to the provided endpoint.
 * Note that this is a sync call even though it is called in an async context.
 * While this is normally frowned upon, it is simply not possible to construct an SSL socket asynchronously in Java.
 * @throws ConnectionFailedException (Sneakily thrown) If the connect attempt fails.
 */
private static Socket createClientSocket(PravegaNodeUri location, ClientConfig clientConfig) {
    try {
        Socket result;
        if (clientConfig.isEnableTlsToSegmentStore()) {
            TrustManagerFactory trustMgrFactory = createFromCert(clientConfig.getTrustStore());
            // Prepare a TLS context that uses the trust manager
            SSLContext tlsContext = SSLContext.getInstance("TLS");
            tlsContext.init(null, trustMgrFactory != null ? trustMgrFactory.getTrustManagers() : null, null);
            SSLSocket tlsClientSocket = (SSLSocket) tlsContext.getSocketFactory().createSocket();
            // SSLSocket does not perform hostname verification by default. So, we must explicitly enable it.
            if (clientConfig.isValidateHostName()) {
                SSLParameters tlsParams = new SSLParameters();
                // While the connection is to a TCP service and not an HTTP server, we use `HTTPS` as the endpoint
                // identification algorithm, which in turn ensures that the SSLSocket will verify the server's host
                // name during TLS handshake. This is a commonly used way of enabling hostname verification
                // regardless of whether the service itself is HTTP (no in this case).
                tlsParams.setEndpointIdentificationAlgorithm("HTTPS");
                tlsClientSocket.setSSLParameters(tlsParams);
            }
            result = tlsClientSocket;
        } else {
            result = new Socket();
        }
        result.setSendBufferSize(TCP_BUFFER_SIZE);
        result.setReceiveBufferSize(TCP_BUFFER_SIZE);
        result.setTcpNoDelay(true);
        result.connect(new InetSocketAddress(location.getEndpoint(), location.getPort()), CONNECTION_TIMEOUT);
        result.setSoTimeout(SOCKET_TIMEOUT_MS);
        return result;
    } catch (Exception e) {
        throw Exceptions.sneakyThrow(new ConnectionFailedException(e));
    }
}
Also used : SSLParameters(javax.net.ssl.SSLParameters) InetSocketAddress(java.net.InetSocketAddress) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) SSLSocket(javax.net.ssl.SSLSocket) SSLContext(javax.net.ssl.SSLContext) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) KeyStoreException(java.security.KeyStoreException) SocketException(java.net.SocketException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) EOFException(java.io.EOFException) InvalidMessageException(io.pravega.shared.protocol.netty.InvalidMessageException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 82 with SSLParameters

use of javax.net.ssl.SSLParameters in project pravega by pravega.

the class ConnectionFactoryImplTest method setUp.

@Before
public void setUp() throws Exception {
    // Configure SSL.
    port = TestUtils.getAvailableListenPort();
    if (ssl) {
        try {
            sslCtx = SslContextBuilder.forServer(new File(SecurityConfigDefaults.TLS_SERVER_CERT_PATH), new File(SecurityConfigDefaults.TLS_SERVER_PRIVATE_KEY_PATH)).build();
        } catch (SSLException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslCtx = null;
    }
    boolean nio = false;
    try {
        bossGroup = new EpollEventLoopGroup(1);
        workerGroup = new EpollEventLoopGroup();
    } catch (ExceptionInInitializerError | UnsatisfiedLinkError | NoClassDefFoundError e) {
        nio = true;
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
    }
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(nio ? NioServerSocketChannel.class : EpollServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            if (sslCtx != null) {
                SslHandler handler = sslCtx.newHandler(ch.alloc());
                SSLEngine sslEngine = handler.engine();
                SSLParameters sslParameters = sslEngine.getSSLParameters();
                sslParameters.setEndpointIdentificationAlgorithm("LDAPS");
                sslEngine.setSSLParameters(sslParameters);
                p.addLast(handler);
            }
        }
    });
    // Start the server.
    serverChannel = b.bind("localhost", port).awaitUninterruptibly().channel();
}
Also used : EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) LoggingHandler(io.netty.handler.logging.LoggingHandler) SSLEngine(javax.net.ssl.SSLEngine) SSLException(javax.net.ssl.SSLException) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) SSLException(javax.net.ssl.SSLException) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler) SSLParameters(javax.net.ssl.SSLParameters) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) File(java.io.File) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Before(org.junit.Before)

Example 83 with SSLParameters

use of javax.net.ssl.SSLParameters 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.getTlsProtocolAllowList(), port.getTlsProtocolDenyList());
    SSLUtil.updateEnabledCipherSuites(sslEngine, port.getTlsCipherSuiteAllowList(), port.getTlsCipherSuiteDenyList());
    if (port.getTlsCipherSuiteAllowList() != null && !port.getTlsCipherSuiteAllowList().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 84 with SSLParameters

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

the class NonBlockingConnectionTLSDelegate method processData.

@Override
public boolean processData() throws IOException {
    if (!_hostChecked) {
        try (QpidByteBuffer buffer = _netInputBuffer.duplicate()) {
            buffer.flip();
            if (SSLUtil.isSufficientToDetermineClientSNIHost(buffer)) {
                final SNIHostName hostName = getSNIHostName(buffer);
                if (hostName != null) {
                    _parent.setSelectedHost(hostName.getAsciiName());
                    SSLParameters sslParameters = _sslEngine.getSSLParameters();
                    sslParameters.setServerNames(Collections.singletonList(hostName));
                    _sslEngine.setSSLParameters(sslParameters);
                }
                _hostChecked = true;
            } else {
                return false;
            }
        }
    }
    _netInputBuffer.flip();
    boolean readData = false;
    boolean tasksRun;
    int oldNetBufferPos;
    do {
        int oldAppBufPos = _applicationBuffer.position();
        oldNetBufferPos = _netInputBuffer.position();
        _status = QpidByteBuffer.decryptSSL(_sslEngine, _netInputBuffer, _applicationBuffer);
        if (_status.getStatus() == SSLEngineResult.Status.CLOSED) {
            int remaining = _netInputBuffer.remaining();
            _netInputBuffer.position(_netInputBuffer.limit());
            // We'd usually expect no more bytes to be sent following a close_notify
            LOGGER.debug("SSLEngine closed, discarded {} byte(s)", remaining);
        }
        tasksRun = runSSLEngineTasks(_status);
        _applicationBuffer.flip();
        if (_applicationBuffer.position() > oldAppBufPos) {
            readData = true;
        }
        _parent.processAmqpData(_applicationBuffer);
        restoreApplicationBufferForWrite();
    } while ((_netInputBuffer.hasRemaining() && (_netInputBuffer.position() > oldNetBufferPos)) || tasksRun);
    if (_netInputBuffer.hasRemaining()) {
        _netInputBuffer.compact();
    } else {
        _netInputBuffer.clear();
    }
    return readData;
}
Also used : SSLParameters(javax.net.ssl.SSLParameters) SNIHostName(javax.net.ssl.SNIHostName) QpidByteBuffer(org.apache.qpid.server.bytebuffer.QpidByteBuffer)

Example 85 with SSLParameters

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

the class JdkSslFactory method createSSLEngine.

/**
 * Create {@link SSLEngine} for given host name and port number.
 * This engine manages the handshake process and encryption/decryption with this remote host.
 * @param peerHost The remote host name
 * @param peerPort The remote port number
 * @param mode The local SSL mode, Client or Server
 * @return SSLEngine
 */
@Override
public SSLEngine createSSLEngine(String peerHost, int peerPort, Mode mode) {
    SSLEngine sslEngine = sslContext.createSSLEngine(peerHost, peerPort);
    if (cipherSuites != null) {
        sslEngine.setEnabledCipherSuites(cipherSuites);
    }
    if (enabledProtocols != null) {
        sslEngine.setEnabledProtocols(enabledProtocols);
    }
    if (mode == Mode.SERVER) {
        sslEngine.setUseClientMode(false);
        switch(clientAuth) {
            case REQUIRED:
                sslEngine.setNeedClientAuth(true);
                break;
            case REQUESTED:
                sslEngine.setWantClientAuth(true);
                break;
        }
    } else {
        sslEngine.setUseClientMode(true);
        SSLParameters sslParams = sslEngine.getSSLParameters();
        sslParams.setEndpointIdentificationAlgorithm(endpointIdentification);
        sslEngine.setSSLParameters(sslParams);
    }
    return sslEngine;
}
Also used : SSLParameters(javax.net.ssl.SSLParameters) SSLEngine(javax.net.ssl.SSLEngine)

Aggregations

SSLParameters (javax.net.ssl.SSLParameters)163 SSLEngine (javax.net.ssl.SSLEngine)48 SSLContext (javax.net.ssl.SSLContext)31 SSLSocket (javax.net.ssl.SSLSocket)31 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)22 InetSocketAddress (java.net.InetSocketAddress)20 IOException (java.io.IOException)19 Test (org.junit.Test)18 Test (org.testng.annotations.Test)18 SNIHostName (javax.net.ssl.SNIHostName)16 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)15 SSLException (javax.net.ssl.SSLException)14 SslHandler (io.netty.handler.ssl.SslHandler)13 CertificateException (java.security.cert.CertificateException)10 ArrayList (java.util.ArrayList)10 X509Certificate (java.security.cert.X509Certificate)9 ByteString (com.linkedin.data.ByteString)8 ChannelPipeline (io.netty.channel.ChannelPipeline)8 SocketChannel (io.netty.channel.socket.SocketChannel)8 SNIServerName (javax.net.ssl.SNIServerName)8