java - 使用 NIO 与 SSL 端口的连接在断开连接后保持建立状态

标签 java ssl connection nio

在我们的应用程序中,我们需要检查某个主机的某些端口是否可用于通信。在此检查阶段,我们不进行真正的通信——我们只需要检查端口是否打开。由于必须同时检查多个端口,我们最初使用 NIO 方法(Selector + SocketChannel 类):

package test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class TestNIO {

    public static void main(final String... params) {
        final List<String> portsToCheck = Arrays.asList(new String[] {"443", "5989"});
        final List<String> openPorts = new ArrayList<String>();
        final String host = "<SOME_IP>";
        final int timeout = 5000;

        Selector selector = null;
        if (!portsToCheck.isEmpty()) {
            try {
                selector = Selector.open();

                for (final String port : portsToCheck) {
                    final SocketChannel channel = SocketChannel.open();
                    channel.configureBlocking(false);
                    channel.connect(new InetSocketAddress(host, Integer.valueOf(port)));
                    channel.register(selector, SelectionKey.OP_CONNECT);
                }

                final int readyChannels = selector.select(timeout);
                if (readyChannels != 0) {
                    final Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                    while (it.hasNext()) {
                        final SelectionKey selKey = it.next();

                        try {
                            if (selKey.isValid() && selKey.isConnectable()) {
                                final SocketChannel channel = (SocketChannel) selKey.channel();
                                try {
                                    if (channel.finishConnect()) {
                                      openPorts.add(String.valueOf(channel.socket().getPort()));
                                    }
                                } catch (final IOException ex) {
                                    ex.printStackTrace();
                                } finally {
                                    channel.close();
                                }
                            }
                        } catch (final Exception ex) {
                            ex.printStackTrace();
                        } finally {
                            selKey.cancel();
                        }
                        it.remove();
                    }
                }
            } catch (final IOException ex) {
                ex.printStackTrace();
            } finally {
                try {
                    if (selector != null && selector.isOpen()) {
                        selector.close();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                System.out.print("Open ports: " + openPorts.toString());
            }
        }
    }
}

这种方法在数百名客户中成功运行了多年,直到我们的一位客户出现问题。也就是说,从客户端(运行此检查的地方,它是 Windows Server 2012 R2)到服务器(它是 ESXi)的连接仅在一个 SSL 端口上保持建立状态,并且在服务器重新启动之前永远不会关闭。这只发生在一个 SSL 端口(标准 443)上,例如另一个 SSL 端口 - 5989(它是 HTTPS CIM 服务器),这不会发生。看起来这是因为 Windows 端的一些配置: 1. 仅发生在几个 HTTPS 端口之一上; 2. 发生在连接到此 Windows 客户端的任何 ESXi 服务器上; 3. 连接到相同 ESXi 服务器的另一个 Windows 客户端不会发生。问题是客户不太愿意配合我们找根源,我们只能自己猜。我们使用另一种经典方法来检查 SSL 端口,即使在这个有问题的系统中也能正常工作。在这里:

package test;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class TestHttpUrlConnection {

    public static void main(final String... params) {
        final List<String> portsToCheck = Arrays.asList(new String[] {"443", "5989"});
        final List<String> openPorts = new ArrayList<String>();
        final String host = "<SOME_IP>";
        final int timeout = 5000;

        if (!portsToCheck.isEmpty()) {
            trustAllHttpsCertificates();
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    return true;
                }
            });

            for (final String port : portsToCheck) {
                HttpsURLConnection connection = null;
                OutputStreamWriter out = null;
                try {
                    connection = (HttpsURLConnection) new URL(
                        "https://" + host + ":" + Integer.valueOf(port)).openConnection();
                    connection.setDoOutput(true);
                    connection.setConnectTimeout(timeout);
                    final OutputStream os = connection.getOutputStream();
                    out = new OutputStreamWriter(os, "UTF8");
                    out.close();
                    openPorts.add(port);
                } catch(final IOException ex) {
                    ex.printStackTrace();
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (final IOException ex) {
                            ex.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
            System.out.print("Open ports: " + openPorts.toString());
        }
    }

    private static void trustAllHttpsCertificates() {
        try {
            final TrustManager[] trustAllCerts = new TrustManager[1]; 
            trustAllCerts[0] = new TrustAllManager();
            final SSLContext sc = SSLContext.getInstance("SSL"); 
            sc.init(null, trustAllCerts, null); 
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (final Exception ex) {
            ex.printStackTrace();
        }
    }

    private static class TrustAllManager implements X509TrustManager {
        public X509Certificate[] getAcceptedIssuers() { 
            return null; 
        }
        public void checkServerTrusted(final X509Certificate[] certs, final String authType) throws CertificateException {
            // Empty
        } 
        public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
            // Empty
        }
    }
}

但是客户希望我们告诉他为什么一种方法有效而另一种方法无效的原因。谁能帮忙?

更新 我发现在那个有问题的系统上,即使遵循代码也会导致每个连接保持 ESTABLISHED 而不会释放回系统的情况。这不是 NIO 并且调用套接字上的显式 close():

Socket sock = new Socket();
SocketAddress serverSocketAddress = new InetSocketAddress(host, port);
try {
    sock.connect(serverSocketAddress, timeout);
    if (sock.isConnected()) {
        openPorts.add(port);
    }
} catch (IOException e) {
    ex.printStackTrace();
} finally {
    if (sock != null) {
        try {
            sock.close();
        } catch (IOException e) {
            ex.printStackTrace();
        }
    }
}

keepAlive 设置为 false 不会改变这种情况。

更新 2

问题也在非 SSL 端口(135,它是 Hyper-V 虚拟化)上重复出现。最让我困惑的是,在重新启动与之建立连接的 guest 操作系统之后,以及在停止打开这些连接的软件之后,它们仍然被标记为在客户端机器上已建立。我认为系统本身确实有问题(与我们的 Java 代码无关),但究竟是什么问题......

更新 3 该问题是由 TrendMicro 的防病毒软件“Virus Buster”引起的。它阻止了连接正常关闭。

最佳答案

在下一次 select() 调用之前,注册 channel 不会完全关闭。这记录在某个地方,我在寻找时永远找不到。

请注意,除了实现根本不安全之外,您的 trustAllCertificates() 方法没有任何用处,并且每个打开的套接字调用一次根本不应该打开的套接字似乎完全没有意义。

关于java - 使用 NIO 与 SSL 端口的连接在断开连接后保持建立状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25053572/

相关文章:

java 正则表达式 字符序列

iis - 对于 IE/XP 支持,使用通配符 SSL 证书是否安全?

java - java中socket的连接问题

R postgres 连接到 RS-DBI 驱动程序中的远程测量错误

mysql - 我的网站上没有用户,但 MySQL 数据库连接数始终为 10+

JavaFX - StackPane 组件跳转

java - 如何确定正在调用哪个 Struts 操作?

ubuntu - Windows 10 WSL(Linux的Windows子系统)上的Ubuntu:无法与WGET和CURL建立SSL连接

ASP.NET 站点通过 SSL 从 Visual Studio 而不是 IIS 连接到远程

java - Amazon CLI 并行部署