This patch fixes a reference issue when SSL_new() fails due to a low memory condition. What happens is that a few error checks end up with a "goto err" statement which calls SSL_free() to clear what was allocated, but since this function first checks that s->references was exactly one before proceeding, the fact that the references is set to 1 only after a successful SSL_new() makes SSL_free() abort() on all prior errors. The proper fix consists in moving the references assignment just after initialization of 's' so that all the error path is properly covered. The error was repeatedly encountered on openssl 1.0.1p. Tests with newer versions were not made yet. (gdb) bt #0 0x0000000000534c5f in SSL_free (s=0x7fa89ee11700) at ssl_lib.c:524 #1 0x00000000005347f6 in SSL_new (ctx=0x274dec8) at ssl_lib.c:393 --- ./ssl/ssl_lib.c.dist 2015-10-27 19:44:01.091392468 +0100 +++ ./ssl/ssl_lib.c 2015-10-27 20:31:57.747630748 +0100 @@ -299,6 +299,7 @@ if (s == NULL) goto err; memset(s, 0, sizeof(SSL)); + s->references = 1; /* to please SSL_free() along the "goto err" path */ #ifndef OPENSSL_NO_KRB5 s->kssl_ctx = kssl_ctx_new(); @@ -375,7 +376,6 @@ if (!s->method->ssl_new(s)) goto err; - s->references = 1; s->server = (ctx->method->ssl_accept == ssl_undefined_function) ? 0 : 1; SSL_clear(s);