C-正确编写和读取使用OpenSSL存储器生物的无效终止字符串的方法



如果您执行以下示例(几乎完全基于官方https://www.openssl.org/docs/man1.0.2/crypto/crypto/bio_s_mem.mem.html#example(:

#include <openssl/bio.h>
#include <openssl/buffer.h>
int main() {
    BIO *mem = BIO_new(BIO_s_mem());
    BIO_puts(mem, "Hello Worldn");
    BUF_MEM *bptr;
    BIO_get_mem_ptr(mem, &bptr);
    BIO_set_close(mem, BIO_NOCLOSE); /* So BIO_free() leaves BUF_MEM alone */
    BIO_free(mem);
    printf("%s", bptr->data);
    BUF_MEM_free(bptr);
    return 0;
}

它只是可能会按预期工作,这取决于n之后的基础内存缓冲区中的未隔离char是偶然的00,并且可以通过Valgrind Report确认:

==17122== Conditional jump or move depends on uninitialised value(s)
==17122==    at 0x52CCCC0: vfprintf (vfprintf.c:1632)
==17122==    by 0x52D3898: printf (printf.c:33)
==17122==    by 0x4008CC: main (test1.c:13)
==17122==  Uninitialised value was created by a heap allocation
==17122==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==17122==    by 0x4E9CE77: CRYPTO_malloc (in /lib/x86_64-linux-gnu/libcrypto.so.1.0.0)
==17122==    by 0x4F4A4B3: BUF_MEM_grow_clean (in /lib/x86_64-linux-gnu/libcrypto.so.1.0.0)
==17122==    by 0x4F4BBDD: mem_write (in /lib/x86_64-linux-gnu/libcrypto.so.1.0.0)
==17122==    by 0x4F4AC8E: BIO_puts (in /lib/x86_64-linux-gnu/libcrypto.so.1.0.0)
==17122==    by 0x40086E: main (test1.c:6)

无论如何,我已经看到这发生了,因为即使BIO_puts也没有将null终止的字符串写入内存生物,即使https://www.openssl.org/docs/man1.0.2/crypto/bio_puts。html说:

bio_puts((尝试将零终止字符串buf写成b。

所以我的问题是用openssl memory bio编写和读取零端的字符串的正确方法。

此外,以这种方式使用此API不会泄漏敏感数据?

注意我正在使用openssl 1.0.2g

bio_puts在字符串中写入所有数据,直到nul终止器 - 但不包括nul终结器本身。而是使用bio_write((:

const char *mystr = "Hello Worldn";
BIO_write(mem, mystr, strlen(mystr) + 1);

或替代:

BIO_puts(mem, "Hello Worldn");
BIO_write(mem, "", 1);

最新更新