From 7754eafb1f2c5c706ca6c8db6c7d271fbe6c040e Mon Sep 17 00:00:00 2001 From: Niels Dossche <7771979+ndossche@users.noreply.github.com> Date: Sat, 17 Jan 2026 12:33:42 +0100 Subject: [PATCH] Fix memory leaks when sk_X509_new_null() fails In a lot of places the return value is not checked, and when the function fails the code continues execution. However, this means that operations on the stack fail and will cause memory leaks on the objects that weren't pushed. We also notice an inconsistency in how these failures are handled. For example, in one place we explicitly have a fatal error `php_error_docref(NULL, E_ERROR, "Memory allocation failure");` but this is the only place to do so. Closes GH-20957. --- NEWS | 3 +++ ext/openssl/openssl.c | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/NEWS b/NEWS index 9b8840c39cd4b..89d5bc0f884ad 100644 --- a/NEWS +++ b/NEWS @@ -30,6 +30,9 @@ PHP NEWS . Fixed bug GH-20818 (Segfault in Tracing JIT with object reference). (khasinski) +- OpenSSL: + . Fix memory leaks when sk_X509_new_null() fails. (ndossche) + - Phar: . Fixed bug GH-20882 (buildFromIterator breaks with missing base directory). (ndossche) diff --git a/ext/openssl/openssl.c b/ext/openssl/openssl.c index e514ebeeaba59..2a502f20688cc 100644 --- a/ext/openssl/openssl.c +++ b/ext/openssl/openssl.c @@ -2552,6 +2552,9 @@ static STACK_OF(X509) *php_array_to_X509_sk(zval * zcerts, uint32_t arg_num, con bool free_cert; sk = sk_X509_new_null(); + if (sk == NULL) { + goto clean_exit; + } /* get certs */ if (Z_TYPE_P(zcerts) == IS_ARRAY) { @@ -5797,6 +5800,9 @@ PHP_FUNCTION(openssl_pkcs7_encrypt) } recipcerts = sk_X509_new_null(); + if (recipcerts == NULL) { + goto clean_exit; + } /* get certs */ if (Z_TYPE_P(zrecipcerts) == IS_ARRAY) { @@ -6404,6 +6410,9 @@ PHP_FUNCTION(openssl_cms_encrypt) } recipcerts = sk_X509_new_null(); + if (recipcerts == NULL) { + goto clean_exit; + } /* get certs */ if (Z_TYPE_P(zrecipcerts) == IS_ARRAY) {