"openssl s_client -connect" 握手后退出

"openssl s_client -connect" exit after handshake

我正在尝试测试 SSL 服务器并想检查 SSL 服务器是否支持特定密码。

为此,我正在使用以下命令 = openssl s_client -connect google.com:443 -cipher RC4-SHA 并从 Java 程序调用它,如下所示并且工作得很好,除了我的 Java 程序永远不会退出,因为openssl 启动的进程仍在运行。

        Process process = Runtime.getRuntime().exec("openssl s_client -connect google.com:443");
        System.out.println("Waiting for process to terminate ...");
        process.waitFor();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = "";
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        System.out.println("Exiting ...");

我看到有类似 openssl s_client -connect google.com:443 -verify 0 的东西,但这是错误 return 代码,并没有获取我正在寻找的信息,但是它确实停止了 openssl 进程。

客户端-服务器握手完成后,有什么方法可以退出 openssl 连接吗?

原来有一个problem with some native openssl client binaries on windows,这意味着你最终得到一个非终止的s_client,即使你关闭了标准输入。如果您从输出中收到已知行,或者从 cygwin 安装中复制所需的二进制文件以使 openssl 的 cygwin 版本毫无问题地升级到 运行,则解决方案将终止。

注意前一段是针对Windows的问题,后面的段落完全可以用于Linux/OSX.

就在 process.waitFor() 之前,我们调用 process.getOutputStream().close() 并关闭 openssl s_client 的输入流;这会触发它的自动终止逻辑。我们也关闭 stderr,以备不时之需。另一件事是在等待进程终止之前移动输出读数,以防缓冲区在 OS 级别被填充。

import java.io.*;

public class props {
    public static void main(String[] args) throws Exception {
        Process process = Runtime.getRuntime().exec("openssl s_client -connect google.com:443");
        process.getOutputStream().close();
        process.getErrorStream().close();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = "";
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        System.out.println("Waiting for process to terminate ...");
        process.waitFor();
        System.out.println("Exiting ...");
    }
};

这是基于 s_client 手册页中 CONNECTED COMMANDS 下的语句,其中指出:

When used interactively (which means neither -quiet nor -ign_eof have been given), the session will be renegotiated if the line begins with an R, and if the line begins with a Q or if end of file is reached, the connection will be closed down.