Skip to content

Commit 7dd24c3

Browse files
danielgustafssonpull[bot]
authored andcommitted
Avoid potential pfree on NULL on OpenSSL errors
Guard against the pointer being NULL before pfreeing upon an error returned from OpenSSL. Also handle errors from X509_NAME_print_ex which can return -1 on memory allocation errors. Backpatch down to v15 where the code was added. Author: Sergey Shinderuk <s.shinderuk@postgrespro.ru> Discussion: https://postgr.es/m/8db5374d-32e0-6abb-d402-40762511eff2@postgrespro.ru Backpatch-through: v15
1 parent a08a2ae commit 7dd24c3

File tree

1 file changed

+17
-8
lines changed

1 file changed

+17
-8
lines changed

src/backend/libpq/be-secure-openssl.c

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -620,8 +620,11 @@ be_tls_open_server(Port *port)
620620
bio = BIO_new(BIO_s_mem());
621621
if (!bio)
622622
{
623-
pfree(port->peer_cn);
624-
port->peer_cn = NULL;
623+
if (port->peer_cn != NULL)
624+
{
625+
pfree(port->peer_cn);
626+
port->peer_cn = NULL;
627+
}
625628
return -1;
626629
}
627630

@@ -632,12 +635,15 @@ be_tls_open_server(Port *port)
632635
* which make regular expression matching a bit easier. Also note that
633636
* it prints the Subject fields in reverse order.
634637
*/
635-
X509_NAME_print_ex(bio, x509name, 0, XN_FLAG_RFC2253);
636-
if (BIO_get_mem_ptr(bio, &bio_buf) <= 0)
638+
if (X509_NAME_print_ex(bio, x509name, 0, XN_FLAG_RFC2253) == -1 ||
639+
BIO_get_mem_ptr(bio, &bio_buf) <= 0)
637640
{
638641
BIO_free(bio);
639-
pfree(port->peer_cn);
640-
port->peer_cn = NULL;
642+
if (port->peer_cn != NULL)
643+
{
644+
pfree(port->peer_cn);
645+
port->peer_cn = NULL;
646+
}
641647
return -1;
642648
}
643649
peer_dn = MemoryContextAlloc(TopMemoryContext, bio_buf->length + 1);
@@ -651,8 +657,11 @@ be_tls_open_server(Port *port)
651657
(errcode(ERRCODE_PROTOCOL_VIOLATION),
652658
errmsg("SSL certificate's distinguished name contains embedded null")));
653659
pfree(peer_dn);
654-
pfree(port->peer_cn);
655-
port->peer_cn = NULL;
660+
if (port->peer_cn != NULL)
661+
{
662+
pfree(port->peer_cn);
663+
port->peer_cn = NULL;
664+
}
656665
return -1;
657666
}
658667

0 commit comments

Comments
 (0)