I'm using OpenSSL's secure heap feature, but not all functions in the library let you specify how memory is allocated. Hence, in some places I'm calling CRYPTO_free on memory allocated with CRYPTO_secure_malloc. It seems to work, although I run out of heap surprisingly quickly (like a 64KiB secure heap is not good enough to generate a 2,048-bit RSA key and a few ECDSA keys), so I wonder if I'm corrupting my heap or leaking memory by freeing it wrong.
My question: can you free memory allocated in either heap with either or CRYPTO_free or CRYPTO_secure_free, or will you get undefined behavior unless you carefully track where every piece of memory may have been allocated? In the latter case, it seems like the secure heap might be more dangerous than not using it, particularly if you are careful about freeing memory using CRYPTO_clear_free, BN_clear_free, EC_POINT_clear_free, etc. Of course, all else equal I want memlock for my sensitive keys, but it seems very hard to keep track of exactly what was allocated how, particularly when various functions return allocated objects. For example, there doesn't even seem to be a BN_secure_free for bignums allocated with BN_secure_new.
can you free memory allocated in either heap with either or CRYPTO_free or CRYPTO_secure_free, or will you get undefined behavior unless you carefully track where every piece of memory may have been allocated?
You must only free memory allocated via CRYPTO_secure_malloc()
with CRYPTO_secure_free()
. If you don't do that the memory will not be released back into the secure heap correctly.
Although the documentation suggests otherwise it is actually possible to call CRYPTO_secure_free(
) on pointers allocated with CRYPTO_malloc()
(the CRYPTO_secure_free()
functions checks where the pointer was allocated via the secure heap or not, and if not falls back to CRYPTO_free()
). It is not possible to do this the other way around (call CRYPTO_free()
with pointers allocated via CRYPTO_secure_malloc()
)
You can also call the function CRYPTO_secure_allocated
which tells you whether or not a pointer was allocated from the secure heap.
See the documentation here:
https://www.openssl.org/docs/man3.2/man3/CRYPTO_secure_allocated.html