Restrict accesses to non-system views and foreign tables during pg_dump.
authorMasahiko Sawada <[email protected]>
Mon, 5 Aug 2024 13:05:17 +0000 (06:05 -0700)
committerMasahiko Sawada <[email protected]>
Mon, 5 Aug 2024 13:05:17 +0000 (06:05 -0700)
When pg_dump retrieves the list of database objects and performs the
data dump, there was possibility that objects are replaced with others
of the same name, such as views, and access them. This vulnerability
could result in code execution with superuser privileges during the
pg_dump process.

This issue can arise when dumping data of sequences, foreign
tables (only 13 or later), or tables registered with a WHERE clause in
the extension configuration table.

To address this, pg_dump now utilizes the newly introduced
restrict_nonsystem_relation_kind GUC parameter to restrict the
accesses to non-system views and foreign tables during the dump
process. This new GUC parameter is added to back branches too, but
these changes do not require cluster recreation.

Back-patch to all supported branches.

Reviewed-by: Noah Misch
Security: CVE-2024-7348
Backpatch-through: 12

13 files changed:
contrib/postgres_fdw/expected/postgres_fdw.out
contrib/postgres_fdw/sql/postgres_fdw.sql
doc/src/sgml/config.sgml
src/backend/foreign/foreign.c
src/backend/optimizer/plan/createplan.c
src/backend/optimizer/util/plancat.c
src/backend/rewrite/rewriteHandler.c
src/backend/tcop/postgres.c
src/backend/utils/misc/guc.c
src/bin/pg_dump/pg_dump.c
src/include/tcop/tcopprot.h
src/test/regress/expected/create_view.out
src/test/regress/sql/create_view.sql

index e71fc93f85b2f880b719a7807eccc48f3546f6f1..ef2c158ecee9101742aee8efde2d26d622ee7fba 100644 (file)
@@ -608,6 +608,15 @@ EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft_empty ORDER BY c1;
    Remote SQL: SELECT c1, c2 FROM public.loct_empty ORDER BY c1 ASC NULLS LAST
 (3 rows)
 
+-- test restriction on non-system foreign tables.
+SET restrict_nonsystem_relation_kind TO 'foreign-table';
+SELECT * from ft1 where c1 < 1; -- ERROR
+ERROR:  access to non-system foreign table is restricted
+INSERT INTO ft1 (c1) VALUES (1); -- ERROR
+ERROR:  access to non-system foreign table is restricted
+DELETE FROM ft1 WHERE c1 = 1; -- ERROR
+ERROR:  access to non-system foreign table is restricted
+RESET restrict_nonsystem_relation_kind;
 -- ===================================================================
 -- WHERE with remotely-executable conditions
 -- ===================================================================
index 1840342a7feadffb9b66c7a8bbdfa226e9e9d0d4..8aa6fd7298a0cb279ea3be5e53b52954a2a55051 100644 (file)
@@ -297,6 +297,13 @@ DELETE FROM loct_empty;
 ANALYZE ft_empty;
 EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft_empty ORDER BY c1;
 
+-- test restriction on non-system foreign tables.
+SET restrict_nonsystem_relation_kind TO 'foreign-table';
+SELECT * from ft1 where c1 < 1; -- ERROR
+INSERT INTO ft1 (c1) VALUES (1); -- ERROR
+DELETE FROM ft1 WHERE c1 = 1; -- ERROR
+RESET restrict_nonsystem_relation_kind;
+
 -- ===================================================================
 -- WHERE with remotely-executable conditions
 -- ===================================================================
index 9ca9d9c27c74d9dffd2453948ba507b133cdb99b..0d545d0401499b240c410055186af6cbc280c2eb 100644 (file)
@@ -8241,6 +8241,23 @@ SET XML OPTION { DOCUMENT | CONTENT };
       </listitem>
      </varlistentry>
 
+     <varlistentry id="guc-restrict-nonsystem-relation-kind" xreflabel="restrict_nonsystem_relation_kind">
+      <term><varname>restrict_nonsystem_relation_kind</varname> (<type>string</type>)
+      <indexterm>
+       <primary><varname>restrict_nonsystem_relation_kind</varname></primary>
+       <secondary>configuration parameter</secondary>
+     </indexterm>
+     </term>
+     <listitem>
+      <para>
+       This variable specifies relation kind to which access is restricted.
+       It contains a comma-separated list of relation kind.  Currently, the
+       supported relation kinds are <literal>view</literal> and
+       <literal>foreign-table</literal>.
+      </para>
+     </listitem>
+     </varlistentry>
+
      </variablelist>
     </sect2>
      <sect2 id="runtime-config-client-format">
index c917ec40ffa32e5871f61554a60ec79777531376..3e8918c7bd1e53e660341312efb1384a066e195d 100644 (file)
@@ -22,6 +22,7 @@
 #include "foreign/foreign.h"
 #include "lib/stringinfo.h"
 #include "miscadmin.h"
+#include "tcop/tcopprot.h"
 #include "utils/builtins.h"
 #include "utils/memutils.h"
 #include "utils/rel.h"
@@ -321,6 +322,15 @@ GetFdwRoutine(Oid fdwhandler)
    Datum       datum;
    FdwRoutine *routine;
 
+   /* Check if the access to foreign tables is restricted */
+   if (unlikely((restrict_nonsystem_relation_kind & RESTRICT_RELKIND_FOREIGN_TABLE) != 0))
+   {
+       /* there must not be built-in FDW handler  */
+       ereport(ERROR,
+               (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+                errmsg("access to non-system foreign table is restricted")));
+   }
+
    datum = OidFunctionCall0(fdwhandler);
    routine = (FdwRoutine *) DatumGetPointer(datum);
 
index 01c042171354bb8b25260e98ff64d1f98e6d3979..e7d50f20b1611625d77afe38168dbafc9859144a 100644 (file)
@@ -40,6 +40,7 @@
 #include "parser/parse_clause.h"
 #include "parser/parsetree.h"
 #include "partitioning/partprune.h"
+#include "tcop/tcopprot.h"
 #include "utils/lsyscache.h"
 
 
@@ -6758,7 +6759,19 @@ make_modifytable(PlannerInfo *root,
 
            Assert(rte->rtekind == RTE_RELATION);
            if (rte->relkind == RELKIND_FOREIGN_TABLE)
+           {
+               /* Check if the access to foreign tables is restricted */
+               if (unlikely((restrict_nonsystem_relation_kind & RESTRICT_RELKIND_FOREIGN_TABLE) != 0))
+               {
+                   /* there must not be built-in foreign tables */
+                   Assert(rte->relid >= FirstNormalObjectId);
+                   ereport(ERROR,
+                           (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+                            errmsg("access to non-system foreign table is restricted")));
+               }
+
                fdwroutine = GetFdwRoutineByRelId(rte->relid);
+           }
            else
                fdwroutine = NULL;
        }
index 937fc36b600a35e24737558b40c1ec317fc713db..d270ed2a9b702587da97730764c39da878031e84 100644 (file)
@@ -46,6 +46,7 @@
 #include "rewrite/rewriteManip.h"
 #include "statistics/statistics.h"
 #include "storage/bufmgr.h"
+#include "tcop/tcopprot.h"
 #include "utils/builtins.h"
 #include "utils/lsyscache.h"
 #include "utils/partcache.h"
@@ -450,6 +451,17 @@ get_relation_info(PlannerInfo *root, Oid relationObjectId, bool inhparent,
    /* Grab foreign-table info using the relcache, while we have it */
    if (relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
    {
+       /* Check if the access to foreign tables is restricted */
+       if (unlikely((restrict_nonsystem_relation_kind & RESTRICT_RELKIND_FOREIGN_TABLE) != 0))
+       {
+           /* there must not be built-in foreign tables */
+           Assert(RelationGetRelid(relation) >= FirstNormalObjectId);
+
+           ereport(ERROR,
+                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+                    errmsg("access to non-system foreign table is restricted")));
+       }
+
        rel->serverid = GetForeignServerIdByRelId(RelationGetRelid(relation));
        rel->fdwroutine = GetFdwRoutineForRelation(relation, true);
    }
index 2b38ea93adcd19cabf11ee1e895ae6010c9e77d1..89fb658f191daad47a08e823bdb44aa88125dbb6 100644 (file)
@@ -40,6 +40,7 @@
 #include "rewrite/rewriteHandler.h"
 #include "rewrite/rewriteManip.h"
 #include "rewrite/rowsecurity.h"
+#include "tcop/tcopprot.h"
 #include "utils/builtins.h"
 #include "utils/lsyscache.h"
 #include "utils/rel.h"
@@ -1713,6 +1714,14 @@ ApplyRetrieveRule(Query *parsetree,
    if (rule->qual != NULL)
        elog(ERROR, "cannot handle qualified ON SELECT rule");
 
+   /* Check if the expansion of non-system views are restricted */
+   if (unlikely((restrict_nonsystem_relation_kind & RESTRICT_RELKIND_VIEW) != 0 &&
+                RelationGetRelid(relation) >= FirstNormalObjectId))
+       ereport(ERROR,
+               (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+                errmsg("access to non-system view \"%s\" is restricted",
+                       RelationGetRelationName(relation))));
+
    if (rt_index == parsetree->resultRelation)
    {
        /*
@@ -3090,6 +3099,14 @@ rewriteTargetView(Query *parsetree, Relation view)
        }
    }
 
+   /* Check if the expansion of non-system views are restricted */
+   if (unlikely((restrict_nonsystem_relation_kind & RESTRICT_RELKIND_VIEW) != 0 &&
+                RelationGetRelid(view) >= FirstNormalObjectId))
+       ereport(ERROR,
+               (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+                errmsg("access to non-system view \"%s\" is restricted",
+                       RelationGetRelationName(view))));
+
    /*
     * For INSERT/UPDATE the modified columns must all be updatable.
     */
index e30197c2f16ad4610bb9a76bc9e05aba686ab878..ea41039604b18b100893f028c7e58cfa2a361c4a 100644 (file)
@@ -77,6 +77,7 @@
 #include "utils/timeout.h"
 #include "utils/timestamp.h"
 #include "mb/pg_wchar.h"
+#include "utils/varlena.h"
 
 
 /* ----------------
@@ -100,6 +101,8 @@ int         max_stack_depth = 100;
 int            PostAuthDelay = 0;
 
 
+/* flags for non-system relation kinds to restrict use */
+int            restrict_nonsystem_relation_kind;
 
 /* ----------------
  *     private variables
@@ -3371,6 +3374,66 @@ assign_max_stack_depth(int newval, void *extra)
    max_stack_depth_bytes = newval_bytes;
 }
 
+/*
+ * GUC check_hook for restrict_nonsystem_relation_kind
+ */
+bool
+check_restrict_nonsystem_relation_kind(char **newval, void **extra, GucSource source)
+{
+   char       *rawstring;
+   List       *elemlist;
+   ListCell   *l;
+   int         flags = 0;
+
+   /* Need a modifiable copy of string */
+   rawstring = pstrdup(*newval);
+
+   if (!SplitIdentifierString(rawstring, ',', &elemlist))
+   {
+       /* syntax error in list */
+       GUC_check_errdetail("List syntax is invalid.");
+       pfree(rawstring);
+       list_free(elemlist);
+       return false;
+   }
+
+   foreach(l, elemlist)
+   {
+       char       *tok = (char *) lfirst(l);
+
+       if (pg_strcasecmp(tok, "view") == 0)
+           flags |= RESTRICT_RELKIND_VIEW;
+       else if (pg_strcasecmp(tok, "foreign-table") == 0)
+           flags |= RESTRICT_RELKIND_FOREIGN_TABLE;
+       else
+       {
+           GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
+           pfree(rawstring);
+           list_free(elemlist);
+           return false;
+       }
+   }
+
+   pfree(rawstring);
+   list_free(elemlist);
+
+   /* Save the flags in *extra, for use by the assign function */
+   *extra = malloc(sizeof(int));
+   *((int *) *extra) = flags;
+
+   return true;
+}
+
+/*
+ * GUC assign_hook for restrict_nonsystem_relation_kind
+ */
+void
+assign_restrict_nonsystem_relation_kind(const char *newval, void *extra)
+{
+   int        *flags = (int *) extra;
+
+   restrict_nonsystem_relation_kind = *flags;
+}
 
 /*
  * set_debug_options --- apply "-d N" command line option
index f4ca61201480b475069c5c2425091e3871c4aa92..b0c29a15ec49bab48263abf9ea220f276fe0f820 100644 (file)
@@ -581,6 +581,7 @@ static char *recovery_target_string;
 static char *recovery_target_xid_string;
 static char *recovery_target_name_string;
 static char *recovery_target_lsn_string;
+static char *restrict_nonsystem_relation_kind_string;
 
 
 /* should be static, but commands/variable.c needs to get at this */
@@ -4211,6 +4212,17 @@ static struct config_string ConfigureNamesString[] =
        NULL, NULL, NULL
    },
 
+   {
+       {"restrict_nonsystem_relation_kind", PGC_USERSET, CLIENT_CONN_STATEMENT,
+           gettext_noop("Sets relation kinds of non-system relation to restrict use"),
+           NULL,
+           GUC_LIST_INPUT | GUC_NOT_IN_SAMPLE
+       },
+       &restrict_nonsystem_relation_kind_string,
+       "",
+       check_restrict_nonsystem_relation_kind, assign_restrict_nonsystem_relation_kind, NULL
+   },
+
    /* End-of-list marker */
    {
        {NULL, 0, 0, NULL, NULL}, NULL, NULL, NULL, NULL, NULL
index 1ac09fa161da77b35886c273d29076fc4832285d..67a3714c62ca4a1986b4755197a6f7164735ced7 100644 (file)
@@ -297,6 +297,7 @@ static void appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
 static char *get_synchronized_snapshot(Archive *fout);
 static void setupDumpWorker(Archive *AHX);
 static TableInfo *getRootTableInfo(TableInfo *tbinfo);
+static void set_restrict_relation_kind(Archive *AH, const char *value);
 static bool forcePartitionRootLoad(const TableInfo *tbinfo);
 
 
@@ -1169,6 +1170,13 @@ setup_connection(Archive *AH, const char *dumpencoding,
            ExecuteSqlStatement(AH, "SET row_security = off");
    }
 
+   /*
+    * For security reasons, we restrict the expansion of non-system views and
+    * access to foreign tables during the pg_dump process. This restriction
+    * is adjusted when dumping foreign table data.
+    */
+   set_restrict_relation_kind(AH, "view, foreign-table");
+
    /*
     * Start transaction-snapshot mode transaction to dump consistent data.
     */
@@ -1842,6 +1850,10 @@ dumpTableData_copy(Archive *fout, void *dcontext)
 
    if (tdinfo->filtercond)
    {
+       /* Temporary allows to access to foreign tables to dump data */
+       if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
+           set_restrict_relation_kind(fout, "view");
+
        /* Note: this syntax is only supported in 8.2 and up */
        appendPQExpBufferStr(q, "COPY (SELECT ");
        /* klugery to get rid of parens in column list */
@@ -1953,6 +1965,11 @@ dumpTableData_copy(Archive *fout, void *dcontext)
                       classname);
 
    destroyPQExpBuffer(q);
+
+   /* Revert back the setting */
+   if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
+       set_restrict_relation_kind(fout, "view, foreign-table");
+
    return 1;
 }
 
@@ -1979,6 +1996,10 @@ dumpTableData_insert(Archive *fout, void *dcontext)
    int         rows_per_statement = dopt->dump_inserts;
    int         rows_this_statement = 0;
 
+   /* Temporary allows to access to foreign tables to dump data */
+   if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
+       set_restrict_relation_kind(fout, "view");
+
    /*
     * If we're going to emit INSERTs with column names, the most efficient
     * way to deal with generated columns is to exclude them entirely.  For
@@ -2218,6 +2239,10 @@ dumpTableData_insert(Archive *fout, void *dcontext)
        destroyPQExpBuffer(insertStmt);
    free(attgenerated);
 
+   /* Revert back the setting */
+   if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
+       set_restrict_relation_kind(fout, "view, foreign-table");
+
    return 1;
 }
 
@@ -4220,6 +4245,28 @@ is_superuser(Archive *fout)
    return false;
 }
 
+/*
+ * Set the given value to restrict_nonsystem_relation_kind value. Since
+ * restrict_nonsystem_relation_kind is introduced in minor version releases,
+ * the setting query is effective only where available.
+ */
+static void
+set_restrict_relation_kind(Archive *AH, const char *value)
+{
+   PQExpBuffer query = createPQExpBuffer();
+   PGresult   *res;
+
+   appendPQExpBuffer(query,
+                     "SELECT set_config(name, '%s', false) "
+                     "FROM pg_settings "
+                     "WHERE name = 'restrict_nonsystem_relation_kind'",
+                     value);
+   res = ExecuteSqlQuery(AH, query->data, PGRES_TUPLES_OK);
+
+   PQclear(res);
+   destroyPQExpBuffer(query);
+}
+
 /*
  * getSubscriptions
  *   get information about subscriptions
index ec21f7e45c5715196d2b57d698cededd26f4fc3f..7e99f415f50c1d8714eed9a5b06019f37879410b 100644 (file)
@@ -42,6 +42,12 @@ typedef enum
 
 extern PGDLLIMPORT int log_statement;
 
+/* Flags for restrict_nonsystem_relation_kind value */
+#define RESTRICT_RELKIND_VIEW          0x01
+#define RESTRICT_RELKIND_FOREIGN_TABLE 0x02
+
+extern PGDLLIMPORT int restrict_nonsystem_relation_kind;
+
 extern List *pg_parse_query(const char *query_string);
 extern List *pg_analyze_and_rewrite(RawStmt *parsetree,
                                    const char *query_string,
@@ -59,6 +65,9 @@ extern List *pg_plan_queries(List *querytrees, int cursorOptions,
 
 extern bool check_max_stack_depth(int *newval, void **extra, GucSource source);
 extern void assign_max_stack_depth(int newval, void *extra);
+extern bool check_restrict_nonsystem_relation_kind(char **newval, void **extra,
+                                                  GucSource source);
+extern void assign_restrict_nonsystem_relation_kind(const char *newval, void *extra);
 
 extern void die(SIGNAL_ARGS);
 extern void quickdie(SIGNAL_ARGS) pg_attribute_noreturn();
index b35faa87cb30545dd36cca174c61a6f32605627b..f2f1cee6b1e9fbd992b8254477c3bdca5ac57d55 100644 (file)
@@ -1799,6 +1799,21 @@ CREATE RULE "_RETURN" AS ON SELECT TO tt28 DO INSTEAD SELECT * FROM tt26;
 CREATE RULE "_RETURN" AS ON SELECT TO tt28 DO INSTEAD SELECT * FROM tt26;
 ERROR:  "tt28" is already a view
 ROLLBACK;
+-- test restriction on non-system view expansion.
+create table tt27v_tbl (a int);
+create view tt27v as select a from tt27v_tbl;
+set restrict_nonsystem_relation_kind to 'view';
+select a from tt27v where a > 0; -- Error
+ERROR:  access to non-system view "tt27v" is restricted
+insert into tt27v values (1); -- Error
+ERROR:  access to non-system view "tt27v" is restricted
+select viewname from pg_views where viewname = 'tt27v'; -- Ok to access a system view.
+ viewname 
+----------
+ tt27v
+(1 row)
+
+reset restrict_nonsystem_relation_kind;
 -- clean up all the random objects we made above
 DROP SCHEMA temp_view_test CASCADE;
 NOTICE:  drop cascades to 27 other objects
@@ -1830,7 +1845,7 @@ drop cascades to view aliased_view_2
 drop cascades to view aliased_view_3
 drop cascades to view aliased_view_4
 DROP SCHEMA testviewschm2 CASCADE;
-NOTICE:  drop cascades to 65 other objects
+NOTICE:  drop cascades to 67 other objects
 DETAIL:  drop cascades to table t1
 drop cascades to view temporal1
 drop cascades to view temporal2
@@ -1896,3 +1911,5 @@ drop cascades to view tt21v
 drop cascades to view tt22v
 drop cascades to view tt23v
 drop cascades to table tt26
+drop cascades to table tt27v_tbl
+drop cascades to view tt27v
index 0ba9d5a6b097a3ea6101fd415dcb9213dbc62e53..c9cefe2515237aedff4d3020bef2ecf8c0454a92 100644 (file)
@@ -630,6 +630,14 @@ CREATE RULE "_RETURN" AS ON SELECT TO tt28 DO INSTEAD SELECT * FROM tt26;
 CREATE RULE "_RETURN" AS ON SELECT TO tt28 DO INSTEAD SELECT * FROM tt26;
 ROLLBACK;
 
+-- test restriction on non-system view expansion.
+create table tt27v_tbl (a int);
+create view tt27v as select a from tt27v_tbl;
+set restrict_nonsystem_relation_kind to 'view';
+select a from tt27v where a > 0; -- Error
+insert into tt27v values (1); -- Error
+select viewname from pg_views where viewname = 'tt27v'; -- Ok to access a system view.
+reset restrict_nonsystem_relation_kind;
 
 -- clean up all the random objects we made above
 DROP SCHEMA temp_view_test CASCADE;