1
0
mirror of https://github.com/postgres/postgres.git synced 2025-07-30 11:03:19 +03:00

Obstruct shell, SQL, and conninfo injection via database and role names.

Due to simplistic quoting and confusion of database names with conninfo
strings, roles with the CREATEDB or CREATEROLE option could escalate to
superuser privileges when a superuser next ran certain maintenance
commands.  The new coding rule for PQconnectdbParams() calls, documented
at conninfo_array_parse(), is to pass expand_dbname=true and wrap
literal database names in a trivial connection string.  Escape
zero-length values in appendConnStrVal().  Back-patch to 9.1 (all
supported versions).

Nathan Bossart, Michael Paquier, and Noah Misch.  Reviewed by Peter
Eisentraut.  Reported by Nathan Bossart.

Security: CVE-2016-5424
This commit is contained in:
Noah Misch
2016-08-08 10:07:46 -04:00
parent d2dd5df514
commit a2385cac13
21 changed files with 572 additions and 193 deletions

View File

@ -218,9 +218,10 @@ issue_warnings(char *sequence_script_file_name)
prep_status("Adjusting sequences");
exec_prog(true,
SYSTEMQUOTE "\"%s/psql\" --set ON_ERROR_STOP=on "
"--no-psqlrc --port %d --username \"%s\" "
"--no-psqlrc --port %d --username %s "
"-f \"%s\" --dbname template1 >> \"%s\"" SYSTEMQUOTE,
new_cluster.bindir, new_cluster.port, os_info.user,
new_cluster.bindir, new_cluster.port,
os_info.user_shell_arg,
sequence_script_file_name, log_opts.filename);
unlink(sequence_script_file_name);
check_ok();

View File

@ -21,10 +21,11 @@ generate_old_dump(void)
* restores the frozenid's for databases and relations.
*/
exec_prog(true,
SYSTEMQUOTE "\"%s/pg_dumpall\" --port %d --username \"%s\" "
SYSTEMQUOTE "\"%s/pg_dumpall\" --port %d --username %s "
"--schema-only --quote-all-identifiers --binary-upgrade "
"-f \"%s/" ALL_DUMP_FILE "\""
SYSTEMQUOTE, new_cluster.bindir, old_cluster.port, os_info.user, os_info.cwd);
SYSTEMQUOTE, new_cluster.bindir, old_cluster.port,
os_info.user_shell_arg, os_info.cwd);
check_ok();
}

View File

@ -52,6 +52,7 @@ parseCommandLine(int argc, char *argv[])
int option; /* Command line option */
int optindex = 0; /* used by getopt_long */
int os_user_effective_id;
PQExpBufferData userbuf;
user_opts.transfer_mode = TRANSFER_MODE_COPY;
@ -211,6 +212,11 @@ parseCommandLine(int argc, char *argv[])
"old cluster data resides");
validateDirectoryOption(&new_cluster.pgdata, "NEWDATADIR", "-D",
"new cluster data resides");
initPQExpBuffer(&userbuf);
appendShellString(&userbuf, os_info.user);
/* Abandon struct, but keep its buffer until process exit. */
os_info.user_shell_arg = userbuf.data;
}

View File

@ -359,9 +359,9 @@ prepare_new_cluster(void)
*/
prep_status("Analyzing all rows in the new cluster");
exec_prog(true,
SYSTEMQUOTE "\"%s/vacuumdb\" --port %d --username \"%s\" "
SYSTEMQUOTE "\"%s/vacuumdb\" --port %d --username %s "
"--all --analyze >> \"%s\" 2>&1" SYSTEMQUOTE,
new_cluster.bindir, new_cluster.port, os_info.user,
new_cluster.bindir, new_cluster.port, os_info.user_shell_arg,
#ifndef WIN32
log_opts.filename
#else
@ -378,9 +378,9 @@ prepare_new_cluster(void)
*/
prep_status("Freezing all rows on the new cluster");
exec_prog(true,
SYSTEMQUOTE "\"%s/vacuumdb\" --port %d --username \"%s\" "
SYSTEMQUOTE "\"%s/vacuumdb\" --port %d --username %s "
"--all --freeze >> \"%s\" 2>&1" SYSTEMQUOTE,
new_cluster.bindir, new_cluster.port, os_info.user,
new_cluster.bindir, new_cluster.port, os_info.user_shell_arg,
#ifndef WIN32
log_opts.filename
#else
@ -421,9 +421,10 @@ prepare_new_databases(void)
exec_prog(true,
SYSTEMQUOTE "\"%s/psql\" --set ON_ERROR_STOP=on "
/* --no-psqlrc prevents AUTOCOMMIT=off */
"--no-psqlrc --port %d --username \"%s\" "
"--no-psqlrc --port %d --username %s "
"-f \"%s/%s\" --dbname template1 >> \"%s\"" SYSTEMQUOTE,
new_cluster.bindir, new_cluster.port, os_info.user, os_info.cwd,
new_cluster.bindir, new_cluster.port,
os_info.user_shell_arg, os_info.cwd,
GLOBALS_DUMP_FILE,
#ifndef WIN32
log_opts.filename
@ -458,9 +459,10 @@ create_new_objects(void)
prep_status("Restoring database schema to new cluster");
exec_prog(true,
SYSTEMQUOTE "\"%s/psql\" --set ON_ERROR_STOP=on "
"--no-psqlrc --port %d --username \"%s\" "
"--no-psqlrc --port %d --username %s "
"-f \"%s/%s\" --dbname template1 >> \"%s\"" SYSTEMQUOTE,
new_cluster.bindir, new_cluster.port, os_info.user, os_info.cwd,
new_cluster.bindir, new_cluster.port,
os_info.user_shell_arg, os_info.cwd,
DB_DUMP_FILE,
#ifndef WIN32
log_opts.filename

View File

@ -14,6 +14,7 @@
#include <sys/time.h>
#include "libpq-fe.h"
#include "pqexpbuffer.h"
/* Allocate for null byte */
#define USER_NAME_SIZE 128
@ -236,6 +237,7 @@ typedef struct
const char *progname; /* complete pathname for this program */
char *exec_path; /* full path to my executable */
char *user; /* username for clusters */
char *user_shell_arg; /* the same, with shell quoting */
char cwd[MAXPGPATH]; /* current working directory, used for output */
char **tablespaces; /* tablespaces */
int num_tablespaces;
@ -381,6 +383,9 @@ void check_pghost_envvar(void);
/* util.c */
char *quote_identifier(const char *s);
extern void appendShellString(PQExpBuffer buf, const char *str);
extern void appendConnStrVal(PQExpBuffer buf, const char *str);
extern void appendPsqlMetaConnect(PQExpBuffer buf, const char *dbname);
int get_user_info(char **user_name);
void check_ok(void);
void report_status(eLogType type, const char *fmt,...);

View File

@ -49,13 +49,20 @@ connectToServer(ClusterInfo *cluster, const char *db_name)
static PGconn *
get_db_conn(ClusterInfo *cluster, const char *db_name)
{
char conn_opts[MAXPGPATH];
PQExpBufferData conn_opts;
PGconn *conn;
snprintf(conn_opts, sizeof(conn_opts),
"dbname = '%s' user = '%s' port = %d", db_name, os_info.user,
cluster->port);
/* Build connection string with proper quoting */
initPQExpBuffer(&conn_opts);
appendPQExpBufferStr(&conn_opts, "dbname=");
appendConnStrVal(&conn_opts, db_name);
appendPQExpBufferStr(&conn_opts, " user=");
appendConnStrVal(&conn_opts, os_info.user);
appendPQExpBuffer(&conn_opts, " port=%d", cluster->port);
return PQconnectdb(conn_opts);
conn = PQconnectdb(conn_opts.data);
termPQExpBuffer(&conn_opts);
return conn;
}

View File

@ -151,6 +151,210 @@ quote_identifier(const char *s)
}
/*
* Append the given string to the shell command being built in the buffer,
* with suitable shell-style quoting to create exactly one argument.
*
* Forbid LF or CR characters, which have scant practical use beyond designing
* security breaches. The Windows command shell is unusable as a conduit for
* arguments containing LF or CR characters. A future major release should
* reject those characters in CREATE ROLE and CREATE DATABASE, because use
* there eventually leads to errors here.
*/
void
appendShellString(PQExpBuffer buf, const char *str)
{
const char *p;
#ifndef WIN32
appendPQExpBufferChar(buf, '\'');
for (p = str; *p; p++)
{
if (*p == '\n' || *p == '\r')
{
fprintf(stderr,
_("shell command argument contains a newline or carriage return: \"%s\"\n"),
str);
exit(EXIT_FAILURE);
}
if (*p == '\'')
appendPQExpBufferStr(buf, "'\"'\"'");
else
appendPQExpBufferChar(buf, *p);
}
appendPQExpBufferChar(buf, '\'');
#else /* WIN32 */
int backslash_run_length = 0;
/*
* A Windows system() argument experiences two layers of interpretation.
* First, cmd.exe interprets the string. Its behavior is undocumented,
* but a caret escapes any byte except LF or CR that would otherwise have
* special meaning. Handling of a caret before LF or CR differs between
* "cmd.exe /c" and other modes, and it is unusable here.
*
* Second, the new process parses its command line to construct argv (see
* https://msdn.microsoft.com/en-us/library/17w5ykft.aspx). This treats
* backslash-double quote sequences specially.
*/
appendPQExpBufferStr(buf, "^\"");
for (p = str; *p; p++)
{
if (*p == '\n' || *p == '\r')
{
fprintf(stderr,
_("shell command argument contains a newline or carriage return: \"%s\"\n"),
str);
exit(EXIT_FAILURE);
}
/* Change N backslashes before a double quote to 2N+1 backslashes. */
if (*p == '"')
{
while (backslash_run_length)
{
appendPQExpBufferStr(buf, "^\\");
backslash_run_length--;
}
appendPQExpBufferStr(buf, "^\\");
}
else if (*p == '\\')
backslash_run_length++;
else
backslash_run_length = 0;
/*
* Decline to caret-escape the most mundane characters, to ease
* debugging and lest we approach the command length limit.
*/
if (!((*p >= 'a' && *p <= 'z') ||
(*p >= 'A' && *p <= 'Z') ||
(*p >= '0' && *p <= '9')))
appendPQExpBufferChar(buf, '^');
appendPQExpBufferChar(buf, *p);
}
/*
* Change N backslashes at end of argument to 2N backslashes, because they
* precede the double quote that terminates the argument.
*/
while (backslash_run_length)
{
appendPQExpBufferStr(buf, "^\\");
backslash_run_length--;
}
appendPQExpBufferStr(buf, "^\"");
#endif /* WIN32 */
}
/*
* Append the given string to the buffer, with suitable quoting for passing
* the string as a value, in a keyword/pair value in a libpq connection
* string
*/
void
appendConnStrVal(PQExpBuffer buf, const char *str)
{
const char *s;
bool needquotes;
/*
* If the string is one or more plain ASCII characters, no need to quote
* it. This is quite conservative, but better safe than sorry.
*/
needquotes = true;
for (s = str; *s; s++)
{
if (!((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') ||
(*s >= '0' && *s <= '9') || *s == '_' || *s == '.'))
{
needquotes = true;
break;
}
needquotes = false;
}
if (needquotes)
{
appendPQExpBufferChar(buf, '\'');
while (*str)
{
/* ' and \ must be escaped by to \' and \\ */
if (*str == '\'' || *str == '\\')
appendPQExpBufferChar(buf, '\\');
appendPQExpBufferChar(buf, *str);
str++;
}
appendPQExpBufferChar(buf, '\'');
}
else
appendPQExpBufferStr(buf, str);
}
/*
* Append a psql meta-command that connects to the given database with the
* then-current connection's user, host and port.
*/
void
appendPsqlMetaConnect(PQExpBuffer buf, const char *dbname)
{
const char *s;
bool complex;
/*
* If the name is plain ASCII characters, emit a trivial "\connect "foo"".
* For other names, even many not technically requiring it, skip to the
* general case. No database has a zero-length name.
*/
complex = false;
for (s = dbname; *s; s++)
{
if (*s == '\n' || *s == '\r')
{
fprintf(stderr,
_("database name contains a newline or carriage return: \"%s\"\n"),
dbname);
exit(EXIT_FAILURE);
}
if (!((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') ||
(*s >= '0' && *s <= '9') || *s == '_' || *s == '.'))
{
complex = true;
}
}
appendPQExpBufferStr(buf, "\\connect ");
if (complex)
{
PQExpBufferData connstr;
initPQExpBuffer(&connstr);
appendPQExpBuffer(&connstr, "dbname=");
appendConnStrVal(&connstr, dbname);
appendPQExpBuffer(buf, "-reuse-previous=on ");
/*
* As long as the name does not contain a newline, SQL identifier
* quoting satisfies the psql meta-command parser. Prefer not to
* involve psql-interpreted single quotes, which behaved differently
* before PostgreSQL 9.2.
*/
appendPQExpBufferStr(buf, quote_identifier(connstr.data));
termPQExpBuffer(&connstr);
}
else
appendPQExpBufferStr(buf, quote_identifier(dbname));
appendPQExpBufferChar(buf, '\n');
}
/*
* get_user_info()
* (copied from initdb.c) find the current user

View File

@ -48,10 +48,16 @@ new_9_0_populate_pg_largeobject_metadata(ClusterInfo *cluster, bool check_mode)
found = true;
if (!check_mode)
{
PQExpBufferData connectbuf;
if (script == NULL && (script = fopen(output_path, "w")) == NULL)
pg_log(PG_FATAL, "could not create necessary file: %s\n", output_path);
fprintf(script, "\\connect %s\n",
quote_identifier(active_db->db_name));
initPQExpBuffer(&connectbuf);
appendPsqlMetaConnect(&connectbuf, active_db->db_name);
fputs(connectbuf.data, script);
termPQExpBuffer(&connectbuf);
fprintf(script,
"SELECT pg_catalog.lo_create(t.loid)\n"
"FROM (SELECT DISTINCT loid FROM pg_catalog.pg_largeobject) AS t;\n");

View File

@ -368,8 +368,13 @@ old_8_3_rebuild_tsvector_tables(ClusterInfo *cluster, bool check_mode)
pg_log(PG_FATAL, "could not create necessary file: %s\n", output_path);
if (!db_used)
{
fprintf(script, "\\connect %s\n\n",
quote_identifier(active_db->db_name));
PQExpBufferData connectbuf;
initPQExpBuffer(&connectbuf);
appendPsqlMetaConnect(&connectbuf, active_db->db_name);
appendPQExpBufferChar(&connectbuf, '\n');
fputs(connectbuf.data, script);
termPQExpBuffer(&connectbuf);
db_used = true;
}
@ -488,8 +493,12 @@ old_8_3_invalidate_hash_gin_indexes(ClusterInfo *cluster, bool check_mode)
pg_log(PG_FATAL, "could not create necessary file: %s\n", output_path);
if (!db_used)
{
fprintf(script, "\\connect %s\n",
quote_identifier(active_db->db_name));
PQExpBufferData connectbuf;
initPQExpBuffer(&connectbuf);
appendPsqlMetaConnect(&connectbuf, active_db->db_name);
fputs(connectbuf.data, script);
termPQExpBuffer(&connectbuf);
db_used = true;
}
fprintf(script, "REINDEX INDEX %s.%s;\n",
@ -613,8 +622,12 @@ old_8_3_invalidate_bpchar_pattern_ops_indexes(ClusterInfo *cluster,
pg_log(PG_FATAL, "could not create necessary file: %s\n", output_path);
if (!db_used)
{
fprintf(script, "\\connect %s\n",
quote_identifier(active_db->db_name));
PQExpBufferData connectbuf;
initPQExpBuffer(&connectbuf);
appendPsqlMetaConnect(&connectbuf, active_db->db_name);
fputs(connectbuf.data, script);
termPQExpBuffer(&connectbuf);
db_used = true;
}
fprintf(script, "REINDEX INDEX %s.%s;\n",
@ -740,8 +753,13 @@ old_8_3_create_sequence_script(ClusterInfo *cluster)
pg_log(PG_FATAL, "could not create necessary file: %s\n", output_path);
if (!db_used)
{
fprintf(script, "\\connect %s\n\n",
quote_identifier(active_db->db_name));
PQExpBufferData connectbuf;
initPQExpBuffer(&connectbuf);
appendPsqlMetaConnect(&connectbuf, active_db->db_name);
appendPQExpBufferChar(&connectbuf, '\n');
fputs(connectbuf.data, script);
termPQExpBuffer(&connectbuf);
db_used = true;
}