Skip to content

Commit a75bd48

Browse files
committed
Clean up quoting of variable strings within replication commands.
Our handling of quoting within replication commands was pretty sloppy, typically looking like appendStringInfo(&cmd, " SLOT \"%s\"", options->slotname); This is fine as long as options->slotname doesn't contain a double quote mark, but what if it does? In principle this'd allow injection of harmful options into replication commands, in the probably-unlikely case that a slot name comes from untrustworthy input. We ought to clean that up. Moreover, even the places that were trying to be more careful generally got it wrong, because they used quoting subroutines intended for SQL commands rather than something that will work with the replication-command scanner repl_scanner.l. For example, several places naively use PQescapeLiteral() to quote option values for replication commands. If the string contains a backslash, PQescapeLiteral() will produce E'...' literal syntax, which repl_scanner.l doesn't recognize. Another near miss was to use quote_identifier() to quote identifiers. That function won't quote valid lowercase identifiers unless they match SQL keywords ... but in this context, replication keywords are what matter. Neither of these errors seem to risk string injection, but they definitely can cause syntax errors in replication commands that ought to be valid. We can clean all this up by using simple quoting logic that just doubles single or double quotes respectively. Or at least, we could if repl_scanner.l handled doubled double quotes in identifiers, but for some reason it doesn't! So the first step in this fix has to be to fix that. (The fact that we'll later reject slot names containing double quotes is very far short of justifying this omission.) Having done that, this patch runs around and applies correct quoting in all places that generate replication commands containing strings coming from outside the immediate context. Probably some of these places are safe because of restrictions elsewhere, but it seems best to just quote all the time. This was originally reported as a security bug, which it could be if replication slot names or parameters were to originate from untrustworthy sources. But the security team concluded that that was a very improbable situation, so we're just going to fix this as a regular bug. Reported-by: Team Dhiutsa Author: Tom Lane <[email protected]> Reviewed-by: Ayush Tiwari <[email protected]> Discussion: https://postgr.es/m/[email protected] Backpatch-through: 14
1 parent 6678b58 commit a75bd48

7 files changed

Lines changed: 159 additions & 73 deletions

File tree

‎src/backend/commands/subscriptioncmds.c‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -518,6 +518,32 @@ parse_subscription_options(ParseState *pstate, List *stmt_options,
518518
}
519519
}
520520

521+
/*
522+
* Append a suitably-quoted identifier or string literal to buf.
523+
* "quote" should be either a double-quote or single-quote character.
524+
*
525+
* Caution: this quoting logic is sufficient for identifiers and literals
526+
* in the replication grammar, but not always in regular SQL. Specifically,
527+
* it'd fail for a string literal if standard_conforming_strings is off.
528+
*/
529+
static void
530+
appendQuotedString(StringInfo buf, const char *str, char quote)
531+
{
532+
appendStringInfoChar(buf, quote);
533+
while (*str)
534+
{
535+
char c = *str++;
536+
537+
if (c == quote)
538+
appendStringInfoChar(buf, c);
539+
appendStringInfoChar(buf, c);
540+
}
541+
appendStringInfoChar(buf, quote);
542+
}
543+
544+
#define appendQuotedIdentifier(b, s) appendQuotedString(b, s, '"')
545+
#define appendQuotedLiteral(b, s) appendQuotedString(b, s, '\'')
546+
521547
/*
522548
* Check that the specified publications are present on the publisher.
523549
*/
@@ -2518,7 +2544,9 @@ ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missi
25182544
load_file("libpqwalreceiver", false);
25192545

25202546
initStringInfo(&cmd);
2521-
appendStringInfo(&cmd, "DROP_REPLICATION_SLOT %s WAIT", quote_identifier(slotname));
2547+
appendStringInfoString(&cmd, "DROP_REPLICATION_SLOT ");
2548+
appendQuotedIdentifier(&cmd, slotname);
2549+
appendStringInfoString(&cmd, " WAIT");
25222550

25232551
PG_TRY();
25242552
{

‎src/backend/replication/libpqwalreceiver/libpqwalreceiver.c‎

Lines changed: 50 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ static WalReceiverFunctionsType PQWalReceiverFunctions = {
116116
};
117117

118118
/* Prototypes for private functions */
119-
static char *stringlist_to_identifierstr(PGconn *conn, List *strings);
119+
static char *stringlist_to_identifierstr(List *strings);
120120

121121
/*
122122
* Module initialization function
@@ -522,6 +522,32 @@ libpqrcv_get_option_from_conninfo(const char *connInfo, const char *keyword)
522522
return option;
523523
}
524524

525+
/*
526+
* Append a suitably-quoted identifier or string literal to buf.
527+
* "quote" should be either a double-quote or single-quote character.
528+
*
529+
* Caution: this quoting logic is sufficient for identifiers and literals
530+
* in the replication grammar, but not always in regular SQL. Specifically,
531+
* it'd fail for a string literal if standard_conforming_strings is off.
532+
*/
533+
static void
534+
appendQuotedString(StringInfo buf, const char *str, char quote)
535+
{
536+
appendStringInfoChar(buf, quote);
537+
while (*str)
538+
{
539+
char c = *str++;
540+
541+
if (c == quote)
542+
appendStringInfoChar(buf, c);
543+
appendStringInfoChar(buf, c);
544+
}
545+
appendStringInfoChar(buf, quote);
546+
}
547+
548+
#define appendQuotedIdentifier(b, s) appendQuotedString(b, s, '"')
549+
#define appendQuotedLiteral(b, s) appendQuotedString(b, s, '\'')
550+
525551
/*
526552
* Start streaming WAL data from given streaming options.
527553
*
@@ -547,8 +573,10 @@ libpqrcv_startstreaming(WalReceiverConn *conn,
547573
/* Build the command. */
548574
appendStringInfoString(&cmd, "START_REPLICATION");
549575
if (options->slotname != NULL)
550-
appendStringInfo(&cmd, " SLOT \"%s\"",
551-
options->slotname);
576+
{
577+
appendStringInfoString(&cmd, " SLOT ");
578+
appendQuotedIdentifier(&cmd, options->slotname);
579+
}
552580

553581
if (options->logical)
554582
appendStringInfoString(&cmd, " LOGICAL");
@@ -563,42 +591,33 @@ libpqrcv_startstreaming(WalReceiverConn *conn,
563591
{
564592
char *pubnames_str;
565593
List *pubnames;
566-
char *pubnames_literal;
567594

568595
appendStringInfoString(&cmd, " (");
569596

570597
appendStringInfo(&cmd, "proto_version '%u'",
571598
options->proto.logical.proto_version);
572599

573600
if (options->proto.logical.streaming_str)
574-
appendStringInfo(&cmd, ", streaming '%s'",
575-
options->proto.logical.streaming_str);
601+
{
602+
appendStringInfoString(&cmd, ", streaming ");
603+
appendQuotedLiteral(&cmd, options->proto.logical.streaming_str);
604+
}
576605

577606
if (options->proto.logical.twophase &&
578607
PQserverVersion(conn->streamConn) >= 150000)
579608
appendStringInfoString(&cmd, ", two_phase 'on'");
580609

581610
if (options->proto.logical.origin &&
582611
PQserverVersion(conn->streamConn) >= 160000)
583-
appendStringInfo(&cmd, ", origin '%s'",
584-
options->proto.logical.origin);
612+
{
613+
appendStringInfoString(&cmd, ", origin ");
614+
appendQuotedLiteral(&cmd, options->proto.logical.origin);
615+
}
585616

586617
pubnames = options->proto.logical.publication_names;
587-
pubnames_str = stringlist_to_identifierstr(conn->streamConn, pubnames);
588-
if (!pubnames_str)
589-
ereport(ERROR,
590-
(errcode(ERRCODE_OUT_OF_MEMORY), /* likely guess */
591-
errmsg("could not start WAL streaming: %s",
592-
pchomp(PQerrorMessage(conn->streamConn)))));
593-
pubnames_literal = PQescapeLiteral(conn->streamConn, pubnames_str,
594-
strlen(pubnames_str));
595-
if (!pubnames_literal)
596-
ereport(ERROR,
597-
(errcode(ERRCODE_OUT_OF_MEMORY), /* likely guess */
598-
errmsg("could not start WAL streaming: %s",
599-
pchomp(PQerrorMessage(conn->streamConn)))));
600-
appendStringInfo(&cmd, ", publication_names %s", pubnames_literal);
601-
PQfreemem(pubnames_literal);
618+
pubnames_str = stringlist_to_identifierstr(pubnames);
619+
appendStringInfoString(&cmd, ", publication_names ");
620+
appendQuotedLiteral(&cmd, pubnames_str);
602621
pfree(pubnames_str);
603622

604623
if (options->proto.logical.binary &&
@@ -899,7 +918,8 @@ libpqrcv_create_slot(WalReceiverConn *conn, const char *slotname,
899918

900919
initStringInfo(&cmd);
901920

902-
appendStringInfo(&cmd, "CREATE_REPLICATION_SLOT \"%s\"", slotname);
921+
appendStringInfoString(&cmd, "CREATE_REPLICATION_SLOT ");
922+
appendQuotedIdentifier(&cmd, slotname);
903923

904924
if (temporary)
905925
appendStringInfoString(&cmd, " TEMPORARY");
@@ -1005,8 +1025,9 @@ libpqrcv_alter_slot(WalReceiverConn *conn, const char *slotname,
10051025
PGresult *res;
10061026

10071027
initStringInfo(&cmd);
1008-
appendStringInfo(&cmd, "ALTER_REPLICATION_SLOT %s ( ",
1009-
quote_identifier(slotname));
1028+
appendStringInfoString(&cmd, "ALTER_REPLICATION_SLOT ");
1029+
appendQuotedIdentifier(&cmd, slotname);
1030+
appendStringInfoString(&cmd, " ( ");
10101031

10111032
if (failover)
10121033
appendStringInfo(&cmd, "FAILOVER %s",
@@ -1203,10 +1224,10 @@ libpqrcv_exec(WalReceiverConn *conn, const char *query,
12031224
*
12041225
* This is essentially the reverse of SplitIdentifierString.
12051226
*
1206-
* The caller should free the result.
1227+
* The caller should pfree the result.
12071228
*/
12081229
static char *
1209-
stringlist_to_identifierstr(PGconn *conn, List *strings)
1230+
stringlist_to_identifierstr(List *strings)
12101231
{
12111232
ListCell *lc;
12121233
StringInfoData res;
@@ -1217,21 +1238,12 @@ stringlist_to_identifierstr(PGconn *conn, List *strings)
12171238
foreach(lc, strings)
12181239
{
12191240
char *val = strVal(lfirst(lc));
1220-
char *val_escaped;
12211241

12221242
if (first)
12231243
first = false;
12241244
else
12251245
appendStringInfoChar(&res, ',');
1226-
1227-
val_escaped = PQescapeIdentifier(conn, val, strlen(val));
1228-
if (!val_escaped)
1229-
{
1230-
free(res.data);
1231-
return NULL;
1232-
}
1233-
appendStringInfoString(&res, val_escaped);
1234-
PQfreemem(val_escaped);
1246+
appendQuotedIdentifier(&res, val);
12351247
}
12361248

12371249
return res.data;

‎src/backend/replication/repl_scanner.l‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,10 @@ UPLOAD_MANIFEST { return K_UPLOAD_MANIFEST; }
197197
return IDENT;
198198
}
199199

200+
<xd>{xddouble} {
201+
addlitchar('"', yyscanner);
202+
}
203+
200204
<xd>{xdinside} {
201205
addlit(yytext, yyleng, yyscanner);
202206
}

‎src/bin/pg_basebackup/pg_recvlogical.c‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -248,8 +248,9 @@ StreamLogicalLog(void)
248248

249249
/* Initiate the replication stream at specified location */
250250
query = createPQExpBuffer();
251-
appendPQExpBuffer(query, "START_REPLICATION SLOT \"%s\" LOGICAL %X/%08X",
252-
replication_slot, LSN_FORMAT_ARGS(startpos));
251+
appendPQExpBufferStr(query, "START_REPLICATION SLOT ");
252+
AppendQuotedIdentifier(query, replication_slot);
253+
appendPQExpBuffer(query, " LOGICAL %X/%08X", LSN_FORMAT_ARGS(startpos));
253254

254255
/* print options if there are any */
255256
if (noptions)
@@ -262,11 +263,14 @@ StreamLogicalLog(void)
262263
appendPQExpBufferStr(query, ", ");
263264

264265
/* write option name */
265-
appendPQExpBuffer(query, "\"%s\"", options[(i * 2)]);
266+
AppendQuotedIdentifier(query, options[i * 2]);
266267

267268
/* write option value if specified */
268-
if (options[(i * 2) + 1] != NULL)
269-
appendPQExpBuffer(query, " '%s'", options[(i * 2) + 1]);
269+
if (options[i * 2 + 1] != NULL)
270+
{
271+
appendPQExpBufferChar(query, ' ');
272+
AppendQuotedLiteral(query, options[i * 2 + 1]);
273+
}
270274
}
271275

272276
if (noptions)

‎src/bin/pg_basebackup/receivelog.c‎

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -452,8 +452,7 @@ CheckServerVersionForStreaming(PGconn *conn)
452452
bool
453453
ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
454454
{
455-
char query[128];
456-
char slotcmd[128];
455+
PQExpBuffer query;
457456
PGresult *res;
458457
XLogRecPtr stoppos;
459458

@@ -478,15 +477,13 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
478477
if (stream->replication_slot != NULL)
479478
{
480479
reportFlushPosition = true;
481-
sprintf(slotcmd, "SLOT \"%s\" ", stream->replication_slot);
482480
}
483481
else
484482
{
485483
if (stream->synchronous)
486484
reportFlushPosition = true;
487485
else
488486
reportFlushPosition = false;
489-
slotcmd[0] = 0;
490487
}
491488

492489
if (stream->sysidentifier != NULL)
@@ -535,8 +532,10 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
535532
*/
536533
if (!existsTimeLineHistoryFile(stream))
537534
{
538-
snprintf(query, sizeof(query), "TIMELINE_HISTORY %u", stream->timeline);
539-
res = PQexec(conn, query);
535+
query = createPQExpBuffer();
536+
appendPQExpBuffer(query, "TIMELINE_HISTORY %u", stream->timeline);
537+
res = PQexec(conn, query->data);
538+
destroyPQExpBuffer(query);
540539
if (PQresultStatus(res) != PGRES_TUPLES_OK)
541540
{
542541
/* FIXME: we might send it ok, but get an error */
@@ -572,11 +571,18 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
572571
return true;
573572

574573
/* Initiate the replication stream at specified location */
575-
snprintf(query, sizeof(query), "START_REPLICATION %s%X/%08X TIMELINE %u",
576-
slotcmd,
577-
LSN_FORMAT_ARGS(stream->startpos),
578-
stream->timeline);
579-
res = PQexec(conn, query);
574+
query = createPQExpBuffer();
575+
appendPQExpBufferStr(query, "START_REPLICATION");
576+
if (stream->replication_slot != NULL)
577+
{
578+
appendPQExpBufferStr(query, " SLOT ");
579+
AppendQuotedIdentifier(query, stream->replication_slot);
580+
}
581+
appendPQExpBuffer(query, " %X/%08X TIMELINE %u",
582+
LSN_FORMAT_ARGS(stream->startpos),
583+
stream->timeline);
584+
res = PQexec(conn, query->data);
585+
destroyPQExpBuffer(query);
580586
if (PQresultStatus(res) != PGRES_COPY_BOTH)
581587
{
582588
pg_log_error("could not send replication command \"%s\": %s",

0 commit comments

Comments
 (0)