gpt4 book ai didi

c - X509 结构的正确释放在链和主证书添加之间是否有所不同?

转载 作者:太空宇宙 更新时间:2023-11-03 12:53:23 25 4
gpt4 key购买 nike

我需要从内存中添加 PEM 类型的证书,这意味着我无法使用内置的文件读取助手。

我的问题是没有关于之后如何释放内存的文档。现在我最好的猜测如下:

SSL_CTX_use_certificate(): //X509 structure SHOULD be freed using X509_free(), as in     SSL_CTX_use_certificate_file()
SSL_CTX_use_PrivateKey() // EVP_KEY structure SHOULD be freed using EVP_KEY_free(), as in SSL_CTX_use_PrivateKey_file()
SSL_CTX_add_extra_chain_cert() // X509 structure SHOULD NOT be freed, as in SSL_CTX_use_certificate_chain_file()

有些时候 grep 源代码似乎表明 SSL_CTX_use_certificate() 会增加引用计数,而 SSL_CTX_add_extra_chain_cert() 不会。

谁能证实或否认我的怀疑?

最佳答案

在 Valgrind 下使用和不使用 X509_free 运行此程序。

#include <stdio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/x509.h>

int main(int argc, char* argv[])
{
unsigned long err;

SSL_library_init();
OpenSSL_add_all_algorithms();

SSL_CTX* ctx = SSL_CTX_new(SSLv23_method());
err = ERR_get_error();
if(ctx == NULL)
{
printf("SSL_CTX_new failed: 0x%lx\n", err);
exit (1);
}

X509* x509 = X509_new();
err = ERR_get_error();
if(x509 == NULL)
{
printf("X509_new failed: 0x%lx\n", err);
exit (1);
}

long res = SSL_CTX_add_extra_chain_cert(ctx, x509);
err = ERR_get_error();
if(res != 1)
{
printf("SSL_CTX_add_extra_chain_cert failed: 0x%lx\n", err);
exit (1);
}

X509_free(x509);
SSL_CTX_free(ctx);

return 0;
}

使用 X509_free(x509) 未注释:

$ valgrind ./openssl-test.exe
==23505== Memcheck, a memory error detector
==23505== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==23505== Using Valgrind-3.9.0 and LibVEX; rerun with -h for copyright info
==23505== Command: ./openssl-test.exe
==23505==
==23505== WARNING: Support on MacOS 10.8 is experimental and mostly broken.
==23505== WARNING: Expect incorrect results, assertions and crashes.
==23505== WARNING: In particular, Memcheck on 32-bit programs will fail to
==23505== WARNING: detect any errors associated with heap-allocated data.
==23505==
==23505== Invalid read of size 4
==23505== at 0x100001AD9: CRYPTO_add_lock (in ./openssl-test.exe)
==23505== by 0x1000BC62A: asn1_item_combine_free (in ./openssl-test.exe)
==23505== by 0x1000BC5A6: ASN1_item_free (in ./openssl-test.exe)
==23505== by 0x10009CC5F: sk_pop_free (in ./openssl-test.exe)
==23505== by 0x100114862: SSL_CTX_free (in ./openssl-test.exe)
==23505== by 0x100001213: main (openssl-test.c:43)
==23505== Address 0x100202dac is 28 bytes inside a block of size 184 free'd
==23505== at 0x7517: free (vg_replace_malloc.c:472)
==23505== by 0x100002634: CRYPTO_free (in ./openssl-test.exe)
==23505== by 0x1000BC95C: asn1_item_combine_free (in ./openssl-test.exe)
==23505== by 0x1000BC5A6: ASN1_item_free (in ./openssl-test.exe)
==23505== by 0x10000120A: main (openssl-test.c:42)
...

关于c - X509 结构的正确释放在链和主证书添加之间是否有所不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24263913/

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