Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C code to clean up memory for openssl EVP_PKEY private keys

I'm starting learn OpenSSL programming in C/C++. An issue I encountered is, how could I safely wipe out the memory for private keys?

For example, I may have code:

EVP_PKEY *private_key = PEM_read_bio_PrivateKey( bio, ,,,)
RSA *r = EVP_PKEY_get1_RSA( private_key);

I'd like to wipe out private_key from memory cleanly before using EVP_PKEY_free() to free it.

I'd appreciate for helps and/or your suggestions. Thanks.

like image 921
pokeba Avatar asked Mar 18 '17 00:03

pokeba


1 Answers

EVP_PKEY *private_key = PEM_read_bio_PrivateKey( bio, ,,,)

I'd like to wipe out private_key from memory cleanly before using EVP_PKEY_free to free it.

OpenSSL's EVP_PKEY_free wipes the private key for you. You don't have to do anything special.

RSA *r = EVP_PKEY_get1_RSA( private_key);

The get1 means the reference count was bumped and you effectively got your own copy of the object. A get0 means you got a pointer to an existing object, and you should not call free on it. Because of get1, you must call RSA_free on it to ensure it gets deleted. As with EVP_PKEY_free, RSA_free will wipe the key.

Please don't call memset. These are opaque structures, and you have to follow a number of pointers to correctly clear the sub-objects. A lot more fields have been hidden in OpenSSL 1.1.0, so its going to be more difficult to follow the pointers (if you wanted to). Also see Error: “invalid use of incomplete type ‘RSA {aka struct rsa_st}” in OpenSSL 1.1.0, Visual Studio and error C2027: use of undefined type 'rsa_st' in OpenSSL 1.1.0, EVP_get_cipherbyname and “undefined struct/union evp_cipher_st” in OpenSSL 1.1.0, etc.


Here's some additional reading you might be interested in:

  • Why does OPENSSL_cleanse look so complex and thread-unsafe?
  • Removing OPENSSL_cleanse from OpenSSL-1.0.1r

When functions like EVP_PKEY_free and RSA_free are called, they eventually end in a call to OPENSSL_cleanse before memory is returned to the operating system. In the case of an RSA private key, its called at leats 8 times to wipe the byte arrays associated with n, e, d, p, q, dp, dq, and invq.

like image 114
jww Avatar answered Oct 15 '22 15:10

jww