Commit 7eb38cd3f54 for php.net
commit 7eb38cd3f543c2fcc30f3bf4abbac341c0ec67ba
Author: Nora Dossche <7771979+ndossche@users.noreply.github.com>
Date: Wed Jan 28 18:37:47 2026 +0100
Fix memory leaks when BN_bin2bn() fails
This is observable in LibreSSL. The code is creating 3 big numbers, but
if one of them failed to create, then DSA_set0_pqg() will have never
executed and there are no references left to the created big numbers,
leaking them in the process.
E.g.:
```
Direct leak of 24 byte(s) in 1 object(s) allocated from:
#0 0x7f4edd402340 in calloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:77
#1 0x7f4edce9d106 in BN_new bn/bn_lib.c:75
#2 0x7f4edce9706c in bn_bin2bn_cbs bn/bn_convert.c:151
#3 0x7f4edce97853 in BN_bin2bn bn/bn_convert.c:206
#4 0x5556bd923e1d in php_openssl_pkey_init_dsa_data /work/php-src/ext/openssl/openssl_backend_v1.c:142
#5 0x5556bd92428f in php_openssl_pkey_init_dsa /work/php-src/ext/openssl/openssl_backend_v1.c:186
#6 0x5556bd8fe079 in zif_openssl_pkey_new /work/php-src/ext/openssl/openssl.c:2042
#7 0x5556be6b44e5 in zend_test_execute_internal /work/php-src/ext/zend_test/observer.c:306
#8 0x5556be9dc85a in ZEND_DO_FCALL_SPEC_RETVAL_USED_HANDLER /work/php-src/Zend/zend_vm_execute.h:2154
#9 0x5556beb3cfa5 in execute_ex /work/php-src/Zend/zend_vm_execute.h:116519
#10 0x5556beb51ec0 in zend_execute /work/php-src/Zend/zend_vm_execute.h:121962
#11 0x5556becb60cc in zend_execute_script /work/php-src/Zend/zend.c:1980
#12 0x5556be6e8ecb in php_execute_script_ex /work/php-src/main/main.c:2645
#13 0x5556be6e92db in php_execute_script /work/php-src/main/main.c:2685
#14 0x5556becbbc37 in do_cli /work/php-src/sapi/cli/php_cli.c:951
#15 0x5556becbe204 in main /work/php-src/sapi/cli/php_cli.c:1362
#16 0x7f4edca671c9 (/lib/x86_64-linux-gnu/libc.so.6+0x2a1c9) (BuildId: 274eec488d230825a136fa9c4d85370fed7a0a5e)
#17 0x7f4edca6728a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2a28a) (BuildId: 274eec488d230825a136fa9c4d85370fed7a0a5e)
#18 0x5556bd809db4 in _start (/work/php-src/build-dbg-asan/sapi/cli/php+0x609db4) (BuildId: 5cc444a6a9fc1a486ea698e72366c16bd5472605)
```
Closes GH-21062.
diff --git a/ext/openssl/openssl.c b/ext/openssl/openssl.c
index 1fa4597393d..bd8e7a94210 100644
--- a/ext/openssl/openssl.c
+++ b/ext/openssl/openssl.c
@@ -4102,7 +4102,14 @@ static bool php_openssl_pkey_init_legacy_dsa(DSA *dsa, zval *data, bool *is_priv
OPENSSL_PKEY_SET_BN(data, p);
OPENSSL_PKEY_SET_BN(data, q);
OPENSSL_PKEY_SET_BN(data, g);
- if (!p || !q || !g || !DSA_set0_pqg(dsa, p, q, g)) {
+ if (!p || !q || !g) {
+ BN_free(p);
+ BN_free(q);
+ BN_free(g);
+ return 0;
+ }
+
+ if (!DSA_set0_pqg(dsa, p, q, g)) {
return 0;
}