gpt4 book ai didi

c++ - 如何使用 OpenSSL 1.1.0 验证主机名?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:43:47 24 4
gpt4 key购买 nike

我正在尝试实现示例 hostname validationOpenSSL .我放在一起的示例 C/C++ 代码是:

// please note I'm connecting to https://openssl.org itself
// enable SNI
if(!SSL_set_tlsext_host_name(ssl, "www.openssl.org")) throw;
if(!SSL_connect(ssl)) throw;
// connection is fine, I can get the homepage via HTTP
X509 *cert = SSL_get_peer_certificate(ssl);
if(cert) {
if(!X509_VERIFY_PARAM_set1_host(SSL_get0_param(ssl), "google.com", 0)) throw;
SSL_set_verify(ssl, SSL_VERIFY_PEER, 0);
const long cert_res = SSL_get_verify_result(ssl);
if(cert_res == X509_V_OK) {
printf("Certificate verified!\n");
}
X509_free(cert);
}

根据上面的代码,我已成功连接到 openssl.org 域;然后我将要验证的名称设置为 google.com 以测试失败,但代码仍然成功

我做错了什么?如何使用 OpenSSL 对主机名进行彻底验证?蜜蜂?我不想重新实现(很可能有错误/错误地)库中已经实现的东西......

我正在使用 Ubuntu 16.04 和这个 libssl 版本:/lib/x86_64-linux-gnu/libssl.so.1.0.0

最佳答案

正如 jww 所建议的,只需设置(至少)

if(!X509_VERIFY_PARAM_set1_host(SSL_get0_param(ssl), "google.com", 0)) throw;

在执行连接本身之前:

if(!SSL_connect(ssl)) throw;

在这种情况下,一种情况是通过添加以下代码确保 OpenSSL 在连接时自动执行检查:

SSL_set_verify(ssl, SSL_VERIFY_PEER, 0);

在调用 SSL_connect 之前,或者按照与之前相同的路径并通过 SSL_get_verify_result 返回 X509_V_ERR_HOSTNAME_MISMATCH 如果想要更详细地处理事情:

// please note I'm connecting to https://openssl.org itself
// enable SNI
if(!SSL_set_tlsext_host_name(ssl, "www.openssl.org")) throw;
// enable name/domain verification
if(!X509_VERIFY_PARAM_set1_host(SSL_get0_param(ssl), "google.com", 0)) throw;
if(!SSL_connect(ssl)) throw;
// get certificate
X509 *cert = SSL_get_peer_certificate(ssl);
if(cert) {
const long cert_res = SSL_get_verify_result(ssl);
// in case of name/domain mismatch cert_res will
// be set as 62 --> X509_V_ERR_HOSTNAME_MISMATCH
if(cert_res != X509_V_OK) throw; // certificate has been tampered with
X509_free(cert);
} else throw; // we couldn't get certificate

关于c++ - 如何使用 OpenSSL 1.1.0 验证主机名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43569773/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com