microsoft / go-crypto-openssl

Go crypto backend for Linux using OpenSSL
MIT License
55 stars 14 forks source link

Free HMAC context when garbage collected #38

Closed qmuntal closed 1 year ago

qmuntal commented 1 year ago

This PR fix a memory leak on NewHMAC(). The returned instance owns a C.GO_HMAC_CTX_PTR allocated using C.malloc. The logic to free the context memory resides in opensslHMAC.finalize, which should be called automatically when the hmac instance is garbage collected.

The problem is that Go doesn't know it has to call opensslHMAC.finalize, we have to instruct it by calling runtime.SetFinalizer(hmac, (*opensslHMAC).finalize) just after instantiating the hmac. And we are not doing that. We used to do it when we initially port RedHat codebase but, at some point, that call was unintentionally removed.

A C.GO_HMAC_CTX_PTR weights around 300 bytes, so we are leaking that amount on every NewHMAC() call, which means ~1GB of memory is lost every 3 milions calls.

Found via fuzzing.