Backport of the upstream commit: https://git.postgresql.org/gitweb/?p=postgresql.git;a=commitdiff;h=2699fc035a75d0774c1f013e9320882287f78adb Fix CVE-2023-5869 diff -ur postgresql-10.23/src/backend/commands/matview.c postgresql-10.23_patch/src/backend/commands/matview.c --- postgresql-10.23/src/backend/commands/matview.c 2022-11-07 22:51:10.000000000 +0100 +++ postgresql-10.23_patch/src/backend/commands/matview.c 2024-02-12 21:22:57.000000000 +0100 @@ -646,14 +646,35 @@ errdetail("Row: %s", SPI_getvalue(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1)))); } - + /* + * Create the temporary "diff" table. + * + * Temporarily switch out of the SECURITY_RESTRICTED_OPERATION context, + * because you cannot create temp tables in SRO context. For extra + * paranoia, add the composite type column only after switching back to + * SRO context. + */ SetUserIdAndSecContext(relowner, save_sec_context | SECURITY_LOCAL_USERID_CHANGE); + resetStringInfo(&querybuf); + appendStringInfo(&querybuf, + "CREATE TEMP TABLE %s (tid pg_catalog.tid)", + diffname); + if (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY) + elog(ERROR, "SPI_exec failed: %s", querybuf.data); + SetUserIdAndSecContext(relowner, + save_sec_context | SECURITY_RESTRICTED_OPERATION); + resetStringInfo(&querybuf); + appendStringInfo(&querybuf, + "ALTER TABLE %s ADD COLUMN newdata %s", + diffname, tempname); + if (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY) + elog(ERROR, "SPI_exec failed: %s", querybuf.data); /* Start building the query for creating the diff table. */ resetStringInfo(&querybuf); appendStringInfo(&querybuf, - "CREATE TEMP TABLE %s AS " + "INSERT INTO %s " "SELECT mv.ctid AS tid, newdata.*::%s AS newdata " "FROM %s mv FULL JOIN %s newdata ON (", diffname, tempname, matviewname, tempname); @@ -783,11 +804,9 @@ "ORDER BY tid"); /* Create the temporary "diff" table. */ - if (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY) + if (SPI_exec(querybuf.data, 0) != SPI_OK_INSERT) elog(ERROR, "SPI_exec failed: %s", querybuf.data); - SetUserIdAndSecContext(relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); /* * We have no further use for data from the "full-data" temp table, but we