ssl - 连接错误后获取证书信息

标签 ssl openssl

我正在使用 OpenSSL 库编写一个简单的 SSL 客户端。我希望能够在连接完成后打印服务器提供的证书链。当连接成功完成时,这不是问题。但是,如果由于某种原因连接失败,我将无法获得服务器提供的失败证书。这是 SSCCE这证明了这一点。

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>

#include <openssl/ssl.h>
#include <openssl/x509_vfy.h>
#include <openssl/err.h>

#define CIPHER_LIST "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"
// #define HOST "google.com" // works
#define HOST "expired.badssl.com" // does not print presented certificate


void print_certificates(SSL *ssl){
    STACK_OF(X509) * sk = SSL_get_peer_cert_chain(ssl);
    X509* cert = NULL;
    char sbuf[1024];
    char ibuf[1024];

    if(sk == NULL){
        printf("Cert chain is null!\n");
    }

    for (int i = 0; i < sk_X509_num(sk); i++) {
        cert = sk_X509_value(sk, i);
        fprintf(stdout, "Subject: %s\n", X509_NAME_oneline(X509_get_subject_name(cert), sbuf, 1024));
        fprintf(stdout, "Issuer: %s\n", X509_NAME_oneline(X509_get_issuer_name(cert), ibuf, 1024));
        PEM_write_X509(stdout, cert);
    }
}

void verify_cert(SSL *ssl, char* host){
    print_certificates(ssl);
    X509* cert = SSL_get_peer_certificate(ssl);
    if(cert) { X509_free(cert); }

    int res = SSL_get_verify_result(ssl);

    if(!(X509_V_OK == res)){
        printf("ERROR (NOT VERIFIED - %s): %s\n", X509_verify_cert_error_string(res), host);
        return;
    }

    printf("SUCCESS: %s\n", host);
    fflush(stdout);

}

int main(int argc, char **argv){
    SSL * ssl = NULL;
    SSL_CTX *ctx = NULL;
    BIO *bio = NULL;
    int res;

    SSL_library_init();
    SSL_load_error_strings();

    const SSL_METHOD* method = SSLv23_method();
    if(method == NULL)
        goto End;

    ctx = SSL_CTX_new(method);
    SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
    if (ctx == NULL)
        goto End;
    SSL_CTX_set_options(ctx, SSL_OP_ALL | SSL_OP_NO_SSLv2 |
        SSL_OP_NO_SSLv3);

    res = SSL_CTX_set_default_verify_paths(ctx);
    if (res != 1)
        goto End;

    bio = BIO_new_ssl_connect(ctx);
    if (bio == NULL)
        return 0;

    BIO_set_conn_hostname(bio, HOST);
    BIO_set_conn_port(bio, "443");
    BIO_set_nbio(bio, 1);

    BIO_get_ssl(bio, &ssl);
    if(ssl == NULL)
        goto End;

    SSL_set_cipher_list(ssl, CIPHER_LIST);
    res = SSL_set_tlsext_host_name(ssl, HOST);

    int still_connecting = 1;
    while(still_connecting){
        int res = SSL_connect(ssl);
        if (res <= 0){
            unsigned long error = SSL_get_error(ssl, res);
            if ( (error != SSL_ERROR_WANT_CONNECT) &&
                 (error != SSL_ERROR_WANT_READ) && (error != SSL_ERROR_WANT_WRITE) )
            {
                printf("Connection encountered fatal error\n");
                ERR_print_errors_fp(stdout);
                still_connecting = 0;
            }
        }
        else{
            printf("Connection completed succesfully\n");
            still_connecting = 0;
        }
    }

    verify_cert(ssl, HOST);

End:
return 0;
}

(编译它的最快方法是 gcc sscce.c -lcrypto -lssl -o sscce )。

每当SSL_connect(ssl) returns 1 (只要连接成功),print_certificates(ssl)按预期工作。但是,如果 SSL_connect(ssl)返回 1 以外的任何值(连接失败),print_certificates(ssl)不打印任何内容,因为 SSL_get_peer_cert_chain(ssl)返回空值。虽然对于不提供证书的服务器来说这是一种合乎逻辑的行为,但在提供无效证书的服务器上,无法访问证书会使调试服务器配置问题变得困难。

有趣的是,SSL_get_verify_result(ssl)连接失败时返回正确的错误代码,尽管我自己无法获得证书链。* 我已经浏览了 OpenSSL 代码库,试图找出原因,而我仍在努力理解所有内容如何组合在一起,看起来 ssl_verify_cert_chain function 中有一些代码那frees the certificates after performing the error checking .我猜在上面的示例代码中,SSL_connect ,一旦它拥有完整的证书链,运行一些内置的验证代码,在证书到达 print_certificates 之前释放证书.这让我很困惑,因为我不明白为什么在验证失败时会释放证书,但在验证成功时不会。也许对 OpenSSL 内部行为有更多了解的人可以对此有所了解。

我注意到股票 s_clientopenssl 提供实用程序在使用 showcerts 选项 ( openssl s_client -showcerts -connect expired.badssl.com:443 ) 运行时不会出现此行为。无论连接成功还是失败,都会打印证书。 print_certificates我的 SSCCE 中的函数只是 s_client cert printing code 的修改版本,但 s_client 不使用 SSL_connect ,所以它表现出不同的行为也就不足为奇了。我注意到 s_client sets a custom certificate verify callback ( defined here ),但我不愿意使用除了默认的**验证功能之外的任何东西。

tl;博士SSL_get_peer_cert_chain(ssl)如果服务器提供无效的证书链,则返回 null。如何解决此问题以打印失败的证书链?

编辑:我已经确认,当我将 BIO 状态设置为阻塞时,这个问题仍然存在,并且(对于它的值(value)),当使用 LibreSSL 编译上述代码时。

编辑 2:我发现创建一个只返回 1 并将其传递给 SSL_CTX_set_verify 的函数因为回调函数(而不是 NULL)导致 SSL_get_peer_cert_chain(ssl)按预期返回证书链,尽管链中的证书无效。但是,我不愿意将此称为问题的解决方案,因为我很明显必须在此处覆盖 OpenSSL 的内置函数之一。

* - 对此的明显 react 是,由于 OpenSSL 告诉我连接失败的原因,我不需要访问原始证书来调试我的问题。在任何其他情况下,这都是正确的,但由于我将此客户端用作涉及 Internet 上使用无效证书的研究项目的一部分,因此我需要能够将失败的证书保存到文件中。

** - 据我所知,将 NULL 作为 SSL_CTX_set_verify 的 verify_callback 参数传递告诉 OpenSSL 使用内置的默认函数进行证书验证。 The documentation在这方面不是很清楚。

最佳答案

TLDR:使用回调。
包括证书链在内的所有 session 参数只有在连接(握手)成功时才可用;这是因为如果握手不成功,就无法确信任何结果都是有效的。理论上,收到的证书可能是一种特殊情况,但一种特殊情况会更复杂,而且您可能已经注意到 OpenSSL API 已经足够复杂,人们经常会使用它。
如你所见 s_client设置一个验证回调,强制接受任何证书链,即使是无效的;这会导致握手成功并且包括证书链在内的参数可用。 s_client旨在作为一种测试工具,无论数据是否真正安全都无关紧要。
如果您只想连接到经过验证的服务器,请使用默认验证逻辑。如果您想连接到未经验证的服务器并处理数据被拦截和/或篡改的风险(在您的情况下可能很小),使用回调 .它是回调的原因是允许应用程序控制。
事实s_client使用 SSL_set_connect_state在第一次数据传输之前引起握手,而不是显式调用 SSL_connect , 无关紧要,没有区别。
已添加:您可以在使用回调后检测到错误——甚至没有!
首先要明确,我们这里说的回调 ('verify' 回调)用于内置链验证逻辑 .有一个不同的回调,名称非常相似,即“证书验证”回调,这是您不想要的。报价 the man page

The actual verification procedure is performed either using the built-in verification procedure or using another application provided verification function set with SSL_CTX_set_cert_verify_callback. The following descriptions apply in the case of the built-in procedure. An application provided procedure also has access to the verify depth information and the verify_callback() function, but the way this information is used may be different.


作为(方便的超链接) SSL_[CTX_]set_cert_verify_callback man page

[by default] the built-in verification function is used. If a verification callback callback [that's clearly a typo] is specified via SSL_CTX_set_cert_verify_callback(), the supplied callback function is called instead. [...]

Providing a complete verification procedure including certificate purpose settings etc is a complex task. The built-in procedure is quite powerful and in most cases it should be sufficient to modify its behaviour using the verify_callback function.


其中“verify_callback 函数”表示set_verify一个不是set_verify_callback一。实际上这并不准确。始终使用部分内置逻辑,只有一部分被证书验证回调替换。但是您仍然不想这样做,只有验证回调。SSL_[CTX_]set_verify[_depth]页面继续描述内置逻辑:

SSL_CTX_set_verify_depth() and SSL_set_verify_depth() set the limit up to which depth certificates in a chain are used during the verification procedure. [...]

The certificate chain is checked starting with the deepest nesting level (the root CA certificate) and worked upward to the peer's certificate. At each level signatures and issuer attributes are checked. Whenever a verification error is found, the error number is stored in x509_ctx and verify_callback is called with preverify_ok=0. [...] If no error is found for a certificate, verify_callback is called with preverify_ok=1 before advancing to the next level.

The return value of verify_callback controls the strategy of the further verification process. If verify_callback returns 0, the verification process is immediately stopped with "verification failed" state. [,,,] If verify_callback returns 1, the verification process is continued. If verify_callback always returns 1, the TLS/SSL handshake will not be terminated with respect to verification failures and the connection will be established. The calling process can however retrieve the error code of the last verification error using SSL_get_verify_result or by maintaining its own error storage managed by verify_callback.

If no verify_callback is specified, the default callback will be used. Its return value is identical to preverify_ok, so that any verification failure will lead to a termination of the TLS/SSL handshake with an alert message, if SSL_VERIFY_PEER is set.


因此,回调可以选择在内置逻辑发现错误后强制接受(调用 0,返回 1)或强制失败,即使内置逻辑认为证书链正常(调用 1,返回 0)但如果它没有不是内置的逻辑控件。s_client 使用的特殊回调(以及 s_server 当使用客户端身份验证时,但这种情况相对较少)打印每个证书的主题名称以及内置逻辑中的状态(标记为“验证返回”),但始终返回 1 从而强制(其余无论发现任何错误,验证和) 连接都将继续。
注意第二段“每当发现验证错误时,错误号存储在 x509_ctx 中,[then] verify_callback 以 preverify_ok=0 调用”和第三段“调用进程可以检索最后一个错误代码使用 SSL_get_verify_result 的验证错误”——即使回调强制 ok=1 也是如此。
但是在检查引用文献时,我发现了 更好的解决方案我在那个页面上错过了:如果你只是默认(或设置)模式 SSL_VERIFY_NONE (添加了强调和说明):

Client mode: if not using an anonymous cipher (by default disabled), the server will send a certificate which will be checked [by the builtin logic, even though NONE would make you think it isn't checked]. The result of the certificate verification process can be checked after the TLS/SSL handshake [is completed] using the SSL_get_verify_result function. The handshake will be continued regardless of the verification result.


这实际上与强制 ok=1 并执行您想要的操作的回调相同。

关于ssl - 连接错误后获取证书信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38705628/

相关文章:

.htaccess - 在整个 CodeIgniter 驱动的站点上强制使用 HTTPS 会创建请求循环……为什么?

Java - 无法通过 url 读取图像

c# - 禁用 AuthenticateAsServer 的证书验证似乎不起作用

c - C 中的 mosquitto 和 SSL/TLS

.net - 禁止使用 TLS session 票证

apache - Apache 上特定 URL 的 SSL 证书

ssl - OpenLDAP - 为 LDAP TLS 连接启用 CRL 检查

c++ - 使用 OpenSSL 将 P1363 编码签名转换为 ECDSA_SIG

tomcat - 将本地 CA 签名的证书导入 tomcat7 keystore.ks 时是否需要第 5 步?

Powershell ISE 错误地将 openssl.exe 正常输出解释为错误