7b3418
From 55f6895f4b4c677272fd4ee1113acdbd99c4b5ab Mon Sep 17 00:00:00 2001
7b3418
From: "Christoph M. Becker" <cmbecker69@gmx.de>
7b3418
Date: Tue, 17 May 2022 12:59:23 +0200
7b3418
Subject: [PATCH] Fix #81720: Uninitialized array in pg_query_params() leading
7b3418
 to RCE
7b3418
7b3418
We must not free parameters which we haven't initialized yet.
7b3418
7b3418
We also fix the not directly related issue, that we checked for the
7b3418
wrong value being `NULL`, potentially causing a segfault.
7b3418
---
7b3418
 ext/pgsql/pgsql.c             |  6 +++---
7b3418
 ext/pgsql/tests/bug81720.phpt | 27 +++++++++++++++++++++++++++
7b3418
 2 files changed, 30 insertions(+), 3 deletions(-)
7b3418
 create mode 100644 ext/pgsql/tests/bug81720.phpt
7b3418
7b3418
diff --git a/ext/pgsql/pgsql.c b/ext/pgsql/pgsql.c
7b3418
index f52ff884d83c..7dcd56cf1441 100644
7b3418
--- a/ext/pgsql/pgsql.c
7b3418
+++ b/ext/pgsql/pgsql.c
7b3418
@@ -1994,7 +1994,7 @@ PHP_FUNCTION(pg_query_params)
7b3418
 				if (Z_TYPE(tmp_val) != IS_STRING) {
7b3418
 					php_error_docref(NULL, E_WARNING,"Error converting parameter");
7b3418
 					zval_ptr_dtor(&tmp_val);
7b3418
-					_php_pgsql_free_params(params, num_params);
7b3418
+					_php_pgsql_free_params(params, i);
7b3418
 					RETURN_FALSE;
7b3418
 				}
7b3418
 				params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val));
7b3418
@@ -5175,8 +5175,8 @@ PHP_FUNCTION(pg_send_execute)
7b3418
 				params[i] = NULL;
7b3418
 			} else {
7b3418
 				zend_string *tmp_str = zval_try_get_string(tmp);
7b3418
-				if (UNEXPECTED(!tmp)) {
7b3418
-					_php_pgsql_free_params(params, num_params);
7b3418
+				if (UNEXPECTED(!tmp_str)) {
7b3418
+					_php_pgsql_free_params(params, i);
7b3418
 					return;
7b3418
 				}
7b3418
 				params[i] = estrndup(ZSTR_VAL(tmp_str), ZSTR_LEN(tmp_str));
7b3418
diff --git a/ext/pgsql/tests/bug81720.phpt b/ext/pgsql/tests/bug81720.phpt
7b3418
new file mode 100644
7b3418
index 000000000000..d79f1fcdd612
7b3418
--- /dev/null
7b3418
+++ b/ext/pgsql/tests/bug81720.phpt
7b3418
@@ -0,0 +1,27 @@
7b3418
+--TEST--
7b3418
+Bug #81720 (Uninitialized array in pg_query_params() leading to RCE)
7b3418
+--SKIPIF--
7b3418
+
7b3418
+--FILE--
7b3418
+
7b3418
+include('config.inc');
7b3418
+
7b3418
+$conn = pg_connect($conn_str);
7b3418
+
7b3418
+try {
7b3418
+    pg_query_params($conn, 'SELECT $1, $2', [1, new stdClass()]);
7b3418
+} catch (Throwable $ex) {
7b3418
+    echo $ex->getMessage(), PHP_EOL;
7b3418
+}
7b3418
+
7b3418
+try {
7b3418
+    pg_send_prepare($conn, "my_query", 'SELECT $1, $2');
7b3418
+    pg_get_result($conn);
7b3418
+    pg_send_execute($conn, "my_query", [1, new stdClass()]);
7b3418
+} catch (Throwable $ex) {
7b3418
+    echo $ex->getMessage(), PHP_EOL;
7b3418
+}
7b3418
+?>
7b3418
+--EXPECT--
7b3418
+Object of class stdClass could not be converted to string
7b3418
+Object of class stdClass could not be converted to string