使用OpenSSL获取整个X509证书链

时间:2017-01-02 19:33:38

标签: c ssl openssl

我正在尝试使用以下代码获取给定域的整个证书链(为简洁起见,删除了错误检查):

int myFunction() {
    for (int i = 0; i < CERTIFICATE_CHAIN_MAXIMUM; i++) {
        certificateChain[i] = NULL;
    }
    numberOfCerts = 0;

    OPENSSL_init();
    SSL_library_init();
    OpenSSL_add_all_ciphers();
    ERR_load_SSL_strings();

    SSL_CTX * ctx = NULL;
    BIO * web = NULL;
    SSL * ssl = NULL;

    ctx = SSL_CTX_new(TLSv1_2_client_method());

    SSL_CTX_set_verify_depth(ctx, CERTIFICATE_CHAIN_MAXIMUM);
    SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback);
    SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION);

    web = BIO_new_ssl_connect(ctx);

    BIO_set_conn_hostname(web, host) // host defined elasewhere
    BIO_get_ssl(web, &ssl);

    const char* const PREFERRED_CIPHERS = "HIGH:!aNULL:!MD5:!RC4";
    SSL_set_cipher_list(ssl, PREFERRED_CIPHERS)

    SSL_set_tlsext_host_name(ssl, [URL.host UTF8String])
    BIO_do_connect(web)
    BIO_do_handshake(web)
}

int verify_callback(int preverify, X509_STORE_CTX* x509_ctx)
{
    STACK_OF(X509) * certs = X509_STORE_CTX_get1_chain(x509_ctx);
    X509 * cert;
    for (int i = 0, count = sk_X509_num(certs); i < count; i++) {
        if (i < CERTIFICATE_CHAIN_MAXIMUM) {
            cert = sk_X509_value(certs, i);
            if (cert != NULL) {
                certificateChain[i] = cert;
                numberOfCerts ++;
            }
        } else {
            printf("Certificate chain maximum exceeded.");
        }
    }

    return preverify;
}

我遇到的问题是我只获取客户端证书和中间CA,而不是根CA.

例如,github.com的证书链是:

DigiCert High Assurance EV Root CA
> DigiCert SHA2 Extended Validation Server CA
  > github.com

但是凭我的代码,我最终只得到:

DigiCert SHA2 Extended Validation Server CA
> github.com

我假设问题是我必须以递归方式获取每个证书的父证书,但是我不确定如何执行此操作并且很难找到有关文档方面的任何帮助。

0 个答案:

没有答案