Skip to content

Commit 9b2015b

Browse files
committed
ext/pgsql: escape table name, delimiter, null marker in pg_copy_from/to
The COPY query embedded table_name with a raw "%s" and the delimiter and null marker inside literal E'..' wrappers, so caller-supplied strings could break out and run side queries. Restrict the bare table_name argument to a plain identifier or schema.table (each side matching [A-Za-z_][A-Za-z0-9_]*) and route it through build_tablename, the same helper pg_insert/update/select/delete have used since bug #62978. Reject anything else with a clear warning so previously silent-fail cases (column lists, ONLY, quoted identifiers) point at the table_name argument instead of surfacing as a Postgres relation lookup error. Pass the delimiter and null marker through PQescapeLiteral. pg_copy_to keeps the parenthesised (query) source form documented in bug 73498; the input is required to start with "(", end with ")", and the matching close paren must be the final character, so the user-supplied string cannot close the wrapper early and inject a trailing statement. Closes GH-21985
1 parent 8d0777e commit 9b2015b

8 files changed

Lines changed: 497 additions & 15 deletions

ext/pgsql/pgsql.c

Lines changed: 144 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,60 @@ static void pgsql_lob_free_obj(zend_object *obj)
273273

274274
/* Compatibility definitions */
275275

276+
static inline zend_result build_tablename(smart_str *querystr, PGconn *pg_link, const zend_string *table);
277+
278+
static bool pgsql_copy_table_name_is_simple(const char *s, size_t len)
279+
{
280+
if (len == 0) {
281+
return false;
282+
}
283+
size_t i = 0;
284+
if (!(isalpha((unsigned char) s[i]) || s[i] == '_')) {
285+
return false;
286+
}
287+
i++;
288+
while (i < len && (isalnum((unsigned char) s[i]) || s[i] == '_')) {
289+
i++;
290+
}
291+
if (i == len) {
292+
return true;
293+
}
294+
if (s[i] != '.') {
295+
return false;
296+
}
297+
i++;
298+
if (i >= len || !(isalpha((unsigned char) s[i]) || s[i] == '_')) {
299+
return false;
300+
}
301+
i++;
302+
while (i < len && (isalnum((unsigned char) s[i]) || s[i] == '_')) {
303+
i++;
304+
}
305+
return i == len;
306+
}
307+
308+
static bool pgsql_copy_query_form_balanced(const char *s, size_t len)
309+
{
310+
if (len < 2 || s[0] != '(' || s[len - 1] != ')') {
311+
return false;
312+
}
313+
int depth = 0;
314+
for (size_t i = 0; i < len; i++) {
315+
if (s[i] == '(') {
316+
depth++;
317+
} else if (s[i] == ')') {
318+
depth--;
319+
if (depth < 0) {
320+
return false;
321+
}
322+
if (depth == 0 && i != len - 1) {
323+
return false;
324+
}
325+
}
326+
}
327+
return depth == 0;
328+
}
329+
276330
static zend_string *_php_pgsql_trim_message(const char *message)
277331
{
278332
size_t i = strlen(message);
@@ -3347,9 +3401,8 @@ PHP_FUNCTION(pg_copy_to)
33473401
pgsql_link_handle *link;
33483402
zend_string *table_name;
33493403
zend_string *pg_delimiter = NULL;
3350-
char *pg_null_as = "\\\\N";
3351-
size_t pg_null_as_len = 0;
3352-
char *query;
3404+
char *pg_null_as = "\\N";
3405+
size_t pg_null_as_len = sizeof("\\N") - 1;
33533406
PGconn *pgsql;
33543407
PGresult *pgsql_result;
33553408
ExecStatusType status;
@@ -3373,14 +3426,56 @@ PHP_FUNCTION(pg_copy_to)
33733426
zend_argument_value_error(3, "must be one character");
33743427
RETURN_THROWS();
33753428
}
3429+
smart_str querystr = {0};
3430+
smart_str_appends(&querystr, "COPY ");
3431+
if (ZSTR_LEN(table_name) > 0 && ZSTR_VAL(table_name)[0] == '(') {
3432+
if (!pgsql_copy_query_form_balanced(ZSTR_VAL(table_name), ZSTR_LEN(table_name))) {
3433+
php_error_docref(NULL, E_WARNING, "Invalid query source '%s': must be a single balanced parenthesised expression", ZSTR_VAL(table_name));
3434+
smart_str_free(&querystr);
3435+
RETURN_FALSE;
3436+
}
3437+
smart_str_appendc(&querystr, '(');
3438+
smart_str_append(&querystr, table_name);
3439+
smart_str_appendc(&querystr, ')');
3440+
} else {
3441+
if (!pgsql_copy_table_name_is_simple(ZSTR_VAL(table_name), ZSTR_LEN(table_name))) {
3442+
php_error_docref(NULL, E_WARNING, "Invalid table_name '%s': must be a plain identifier or schema.table", ZSTR_VAL(table_name));
3443+
smart_str_free(&querystr);
3444+
RETURN_FALSE;
3445+
}
3446+
if (build_tablename(&querystr, pgsql, table_name) == FAILURE) {
3447+
smart_str_free(&querystr);
3448+
RETURN_FALSE;
3449+
}
3450+
}
33763451

3377-
spprintf(&query, 0, "COPY %s TO STDOUT DELIMITER E'%c' NULL AS E'%s'", ZSTR_VAL(table_name), *ZSTR_VAL(pg_delimiter), pg_null_as);
3452+
char *escaped_delimiter = PQescapeLiteral(pgsql, ZSTR_VAL(pg_delimiter), 1);
3453+
if (!escaped_delimiter) {
3454+
zend_string *msgbuf = _php_pgsql_trim_message(PQerrorMessage(pgsql));
3455+
php_error_docref(NULL, E_WARNING, "Failed to escape delimiter '%c': %s", *ZSTR_VAL(pg_delimiter), ZSTR_VAL(msgbuf));
3456+
zend_string_release(msgbuf);
3457+
smart_str_free(&querystr);
3458+
RETURN_FALSE;
3459+
}
3460+
char *escaped_null_as = PQescapeLiteral(pgsql, pg_null_as, pg_null_as_len);
3461+
if (!escaped_null_as) {
3462+
zend_string *msgbuf = _php_pgsql_trim_message(PQerrorMessage(pgsql));
3463+
php_error_docref(NULL, E_WARNING, "Failed to escape null_as '%s': %s", pg_null_as, ZSTR_VAL(msgbuf));
3464+
zend_string_release(msgbuf);
3465+
PQfreemem(escaped_delimiter);
3466+
smart_str_free(&querystr);
3467+
RETURN_FALSE;
3468+
}
3469+
smart_str_append_printf(&querystr, " TO STDOUT DELIMITER %s NULL AS %s", escaped_delimiter, escaped_null_as);
3470+
smart_str_0(&querystr);
3471+
PQfreemem(escaped_delimiter);
3472+
PQfreemem(escaped_null_as);
33783473

33793474
while ((pgsql_result = PQgetResult(pgsql))) {
33803475
PQclear(pgsql_result);
33813476
}
3382-
pgsql_result = PQexec(pgsql, query);
3383-
efree(query);
3477+
pgsql_result = PQexec(pgsql, ZSTR_VAL(querystr.s));
3478+
smart_str_free(&querystr);
33843479

33853480
if (pgsql_result) {
33863481
status = PQresultStatus(pgsql_result);
@@ -3462,9 +3557,8 @@ PHP_FUNCTION(pg_copy_from)
34623557
zval *value;
34633558
zend_string *table_name;
34643559
zend_string *pg_delimiter = NULL;
3465-
char *pg_null_as = "\\\\N";
3466-
size_t pg_null_as_len;
3467-
char *query;
3560+
char *pg_null_as = "\\N";
3561+
size_t pg_null_as_len = sizeof("\\N") - 1;
34683562
PGconn *pgsql;
34693563
PGresult *pgsql_result;
34703564
ExecStatusType status;
@@ -3488,14 +3582,46 @@ PHP_FUNCTION(pg_copy_from)
34883582
zend_argument_value_error(4, "must be one character");
34893583
RETURN_THROWS();
34903584
}
3585+
smart_str querystr = {0};
3586+
smart_str_appends(&querystr, "COPY ");
3587+
if (!pgsql_copy_table_name_is_simple(ZSTR_VAL(table_name), ZSTR_LEN(table_name))) {
3588+
php_error_docref(NULL, E_WARNING, "Invalid table_name '%s': must be a plain identifier or schema.table", ZSTR_VAL(table_name));
3589+
smart_str_free(&querystr);
3590+
RETURN_FALSE;
3591+
}
3592+
if (build_tablename(&querystr, pgsql, table_name) == FAILURE) {
3593+
smart_str_free(&querystr);
3594+
RETURN_FALSE;
3595+
}
3596+
3597+
char *escaped_delimiter = PQescapeLiteral(pgsql, ZSTR_VAL(pg_delimiter), 1);
3598+
if (!escaped_delimiter) {
3599+
zend_string *msgbuf = _php_pgsql_trim_message(PQerrorMessage(pgsql));
3600+
php_error_docref(NULL, E_WARNING, "Failed to escape delimiter '%c': %s", *ZSTR_VAL(pg_delimiter), ZSTR_VAL(msgbuf));
3601+
zend_string_release(msgbuf);
3602+
smart_str_free(&querystr);
3603+
RETURN_FALSE;
3604+
}
3605+
char *escaped_null_as = PQescapeLiteral(pgsql, pg_null_as, pg_null_as_len);
3606+
if (!escaped_null_as) {
3607+
zend_string *msgbuf = _php_pgsql_trim_message(PQerrorMessage(pgsql));
3608+
php_error_docref(NULL, E_WARNING, "Failed to escape null_as '%s': %s", pg_null_as, ZSTR_VAL(msgbuf));
3609+
zend_string_release(msgbuf);
3610+
PQfreemem(escaped_delimiter);
3611+
smart_str_free(&querystr);
3612+
RETURN_FALSE;
3613+
}
3614+
smart_str_append_printf(&querystr, " FROM STDIN DELIMITER %s NULL AS %s", escaped_delimiter, escaped_null_as);
3615+
smart_str_0(&querystr);
3616+
PQfreemem(escaped_delimiter);
3617+
PQfreemem(escaped_null_as);
34913618

3492-
spprintf(&query, 0, "COPY %s FROM STDIN DELIMITER E'%c' NULL AS E'%s'", ZSTR_VAL(table_name), *ZSTR_VAL(pg_delimiter), pg_null_as);
34933619
while ((pgsql_result = PQgetResult(pgsql))) {
34943620
PQclear(pgsql_result);
34953621
}
3496-
pgsql_result = PQexec(pgsql, query);
3622+
pgsql_result = PQexec(pgsql, ZSTR_VAL(querystr.s));
34973623

3498-
efree(query);
3624+
smart_str_free(&querystr);
34993625

35003626
if (pgsql_result) {
35013627
status = PQresultStatus(pgsql_result);
@@ -5574,7 +5700,9 @@ static inline zend_result build_tablename(smart_str *querystr, PGconn *pg_link,
55745700
} else {
55755701
char *escaped = PQescapeIdentifier(pg_link, ZSTR_VAL(table), len);
55765702
if (escaped == NULL) {
5577-
php_error_docref(NULL, E_NOTICE, "Failed to escape table name '%s'", ZSTR_VAL(table));
5703+
zend_string *msgbuf = _php_pgsql_trim_message(PQerrorMessage(pg_link));
5704+
php_error_docref(NULL, E_WARNING, "Failed to escape table name '%s': %s", ZSTR_VAL(table), ZSTR_VAL(msgbuf));
5705+
zend_string_release(msgbuf);
55785706
return FAILURE;
55795707
}
55805708
smart_str_appends(querystr, escaped);
@@ -5590,7 +5718,9 @@ static inline zend_result build_tablename(smart_str *querystr, PGconn *pg_link,
55905718
} else {
55915719
char *escaped = PQescapeIdentifier(pg_link, after_dot, len);
55925720
if (escaped == NULL) {
5593-
php_error_docref(NULL, E_NOTICE, "Failed to escape table name '%s'", ZSTR_VAL(table));
5721+
zend_string *msgbuf = _php_pgsql_trim_message(PQerrorMessage(pg_link));
5722+
php_error_docref(NULL, E_WARNING, "Failed to escape table name '%s': %s", ZSTR_VAL(table), ZSTR_VAL(msgbuf));
5723+
zend_string_release(msgbuf);
55945724
return FAILURE;
55955725
}
55965726
smart_str_appendc(querystr, '.');

ext/pgsql/tests/ghsa-hrwm-9436-5mv3.phpt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ bool(false)
4242
Notice: pg_insert(): String value escaping failed for PostgreSQL 'text' (bar) in %s on line %d
4343
bool(false)
4444

45-
Notice: pg_insert(): Failed to escape table name 'ABC%s';' in %s on line %d
45+
Warning: pg_insert(): Failed to escape table name 'ABC%s';': %s in %s on line %d
4646
bool(false)
4747

4848
Notice: pg_insert(): Failed to escape field 'ABC%s';' in %s on line %d
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
--TEST--
2+
pg_copy_to() / pg_copy_from() default null marker round-trip
3+
--EXTENSIONS--
4+
pgsql
5+
--SKIPIF--
6+
<?php include("inc/skipif.inc"); ?>
7+
--FILE--
8+
<?php
9+
10+
include('inc/config.inc');
11+
12+
$db = pg_connect($conn_str);
13+
pg_query($db, 'DROP TABLE IF EXISTS pg_copy_default_null');
14+
pg_query($db, 'CREATE TABLE pg_copy_default_null (id int, v text)');
15+
pg_query($db, "INSERT INTO pg_copy_default_null VALUES (1, 'hello'), (2, NULL)");
16+
17+
$rows = pg_copy_to($db, 'pg_copy_default_null');
18+
var_dump($rows);
19+
20+
pg_query($db, 'DELETE FROM pg_copy_default_null');
21+
var_dump(pg_copy_from($db, 'pg_copy_default_null', $rows));
22+
var_dump(pg_fetch_all(pg_query($db, 'SELECT v FROM pg_copy_default_null ORDER BY id')));
23+
24+
?>
25+
--CLEAN--
26+
<?php
27+
include('inc/config.inc');
28+
$db = pg_connect($conn_str);
29+
pg_query($db, 'DROP TABLE IF EXISTS pg_copy_default_null');
30+
?>
31+
--EXPECT--
32+
array(2) {
33+
[0]=>
34+
string(8) "1 hello
35+
"
36+
[1]=>
37+
string(5) "2 \N
38+
"
39+
}
40+
bool(true)
41+
array(2) {
42+
[0]=>
43+
array(1) {
44+
["v"]=>
45+
string(5) "hello"
46+
}
47+
[1]=>
48+
array(1) {
49+
["v"]=>
50+
NULL
51+
}
52+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
--TEST--
2+
pg_copy_from() escapes the null_as argument
3+
--EXTENSIONS--
4+
pgsql
5+
--SKIPIF--
6+
<?php include("inc/skipif.inc"); ?>
7+
--FILE--
8+
<?php
9+
10+
include('inc/config.inc');
11+
12+
$db = pg_connect($conn_str);
13+
pg_query($db, 'DROP TABLE IF EXISTS pg_copy_null_as_target');
14+
pg_query($db, 'DROP TABLE IF EXISTS pg_copy_null_as_injected');
15+
pg_query($db, 'CREATE TABLE pg_copy_null_as_target (v text)');
16+
17+
$evil = "X'; CREATE TABLE pg_copy_null_as_injected (v text); --";
18+
var_dump(pg_copy_from($db, 'pg_copy_null_as_target', ["row\n"], "\t", $evil));
19+
20+
$r = pg_query($db, "SELECT 1 FROM pg_tables WHERE tablename = 'pg_copy_null_as_injected'");
21+
var_dump(pg_num_rows($r));
22+
23+
$r = pg_query($db, 'SELECT v FROM pg_copy_null_as_target ORDER BY v');
24+
var_dump(pg_fetch_all($r));
25+
26+
?>
27+
--CLEAN--
28+
<?php
29+
include('inc/config.inc');
30+
$db = pg_connect($conn_str);
31+
pg_query($db, 'DROP TABLE IF EXISTS pg_copy_null_as_target');
32+
pg_query($db, 'DROP TABLE IF EXISTS pg_copy_null_as_injected');
33+
?>
34+
--EXPECT--
35+
bool(true)
36+
int(0)
37+
array(1) {
38+
[0]=>
39+
array(1) {
40+
["v"]=>
41+
string(3) "row"
42+
}
43+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
--TEST--
2+
pg_copy_from() escapes the table name argument
3+
--EXTENSIONS--
4+
pgsql
5+
--SKIPIF--
6+
<?php include("inc/skipif.inc"); ?>
7+
--FILE--
8+
<?php
9+
10+
include('inc/config.inc');
11+
12+
$db = pg_connect($conn_str);
13+
pg_query($db, 'DROP TABLE IF EXISTS pg_copy_from_target');
14+
pg_query($db, 'CREATE TABLE pg_copy_from_target (v text)');
15+
pg_query($db, 'DROP TABLE IF EXISTS pg_copy_from_other');
16+
pg_query($db, 'CREATE TABLE pg_copy_from_other (v text)');
17+
18+
$evil = "pg_copy_from_other FROM STDIN --";
19+
var_dump(pg_copy_from($db, $evil, ["redirected\n"]));
20+
21+
$rows = pg_fetch_all(pg_query($db, 'SELECT v FROM pg_copy_from_other')) ?: [];
22+
var_dump($rows);
23+
24+
?>
25+
--CLEAN--
26+
<?php
27+
include('inc/config.inc');
28+
$db = pg_connect($conn_str);
29+
pg_query($db, 'DROP TABLE IF EXISTS pg_copy_from_target');
30+
pg_query($db, 'DROP TABLE IF EXISTS pg_copy_from_other');
31+
?>
32+
--EXPECTF--
33+
Warning: pg_copy_from(): Invalid table_name 'pg_copy_from_other FROM STDIN --': must be a plain identifier or schema.table in %s on line %d
34+
bool(false)
35+
array(0) {
36+
}

0 commit comments

Comments
 (0)