Reg: Freeing of SSL_CTX object through SSL_free Function

Matt Caswell matt at openssl.org
Wed Apr 13 11:28:45 UTC 2022



On 13/04/2022 11:55, Ram Chandra via openssl-users wrote:
> I am using OpenSSL 1.1.1k Version, From that I see following are done in 
> OpenSSL code, pls correct me if I am wrong.
> 
> 
> Inside SSL_new:
> 
> SSL *SSL_new(SSL_CTX *ctx)
> {
>      SSL *s;
>       .......
>       .......
>       s = OPENSSL_zalloc(sizeof(*s));
>       ....
>       ....
>       SSL_CTX_up_ref(ctx);
>       s->ctx = ctx; /* *ctx* value to *s->ctx* , also gets freed when 
> called SLL_free(s) ==> SSL_CTX_free(s->ctx)*/
>       ....
>       ....
>       SSL_CTX_up_ref(ctx);
>       s->session_ctx = ctx;/* same value is getting assigned here also */
>       .....
>       return s;
> }
> 
> Inside SSL_free:
> void SSL_free(SSL *s)
> {
>       if ( s == NULL)
>             return;
>       X509_VERIFY_PARAM_free(s->param);
>       .....
>       .....
>      SSL_CTX_free( s->session_ctx); /* this holds the value of ctx that 
> was passed t
> o SSL_new(), yes or no? */
>      .....
>      .....
>      SSL_CTX_free( s->ctx); /* this again trying to free the same 
> pointer , abnormal behavior */
> }
> 
> Point here is inside SSL_CTX_free(), after freeing  "s->session_ctx" , 
> we are not setting "s->session_ctx" to NULL(this may be optional, its ok 
> if we don't use the same pointer again), but "s->session_ctx" 
> and "s->ctx" both have same value. So applying "free()" on same value 
> again ( through  SSL_CTX_free( s->ctx); ) will result in abnormal 
> behavior, *correct or not?*
> 

Not correct. SSL_CTX_free() may not actually free the object at all - 
see below.

> I could not understand how OpenSSL *free() *ing pointers if they are 
> assigned to multiple different variables.
> 
> Note: tried going through "SSL_CTX_up_ref(ctx);" , and 
> "SSL_CTX_down_ref(ctx);", looks like they are tracking the pointer usage 
> count by other APIs, but could not understand what exactly they are 
> doing...when count is 0.

SSL_CTX objects are reference counted. So SSL_CTX_up_ref() increments 
the reference count and SSL_CTX_free() decrements it. A reference is 
created for each place that you assign an object to a different 
location. Only when all references are freed (i.e. when the reference 
count drops to 0) does the object itself actually get freed.


Matt

> 
> Could someone please elaborate a bit ..
> 
> Chand..
> 


More information about the openssl-users mailing list