Pooven
Pooven

Reputation: 1764

Releasing OpenSSL resources: SSL_CTX_free

I'm loading certificates from memory, adding it to the certificate store, and then performing validation:

char base64EncodedCert[] = "...";
const int autoDetermineLength = -1;
BIO* memoryCert = BIO_new_mem_buff(base64EncodedCert, autoDetermineLength);
X509* certificate = PEM_read_bio_X509(memoryCert, nullptr, 0, nullptr);
BIO_free(sslCompatibleMemoryCert);
X509_STORE_add_cert(certificateStore, certificate);

Based on the code:

  1. The buffer base64EncodedCert only needs to be in memory for as long as the BIO is needed, as described in the documentation.
  2. Once the certificate is created, the BIO is no longer created and can be freed. This is an observation; looking at the X509 structure, this seems reasonable.
  3. I suspect that the ownership of the X509 object is passed on the the certificate store via X509_STORE_add_cert. That is, I don't need to keep track of the newly created certificate, it is automatically tied to the lifetime of the certificate store.
  4. The certificate store comes from the SSL context, and so its lifetime is tied to the SSL context (SSL_CTX).
  5. It's therefore my conclusion that when I call SSL_CTX_free the certificates I've added to the certificate store are released accordingly.

Am I correct? Are there any other memory considerations? Thank you for your time and contribution.

Upvotes: 1

Views: 752

Answers (1)

sirgeorge
sirgeorge

Reputation: 6531

Answers:

  1. Yes, you are correct
  2. Yes, you are correct
  3. Yes - as long as X509_STORE_add_cert succeded. In other words: if X509_STORE_add_cert returned value greater than zero - ownership of the X509 object is passed on the the certificate store; if X509_STORE_add_cert returned zero - ownership of the X509 object is not passed on the the certificate store - you need to handle that.
  4. Yes - if the certificate store comes from the SSL context
  5. Yes, you are correct

I hope that helps.

Upvotes: 2

Related Questions