如何使用OpenSSL 1.1.0验证主机名

How can I validate hostnames with OpenSSL 1.1.0?

本文关键字:主机 验证 OpenSSL 何使用      更新时间:2023-10-16

我正在尝试使用openSSL实现示例主机名验证。我组合的示例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 API实现彻底验证主机名的验证?我不想重新实施(最有可能使用错误/错误(,库中已经实现了什么...

我正在使用ubuntu 16.04,this 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;

在这种情况下,通过添加以下代码:

来确保OpenSL在连接时间自动实现支票
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