diff options
-rw-r--r-- | src/backend/access/transam/xact.c | 39 | ||||
-rw-r--r-- | src/backend/catalog/index.c | 24 | ||||
-rw-r--r-- | src/backend/commands/analyze.c | 24 | ||||
-rw-r--r-- | src/backend/commands/schemacmds.c | 13 | ||||
-rw-r--r-- | src/backend/commands/tablecmds.c | 12 | ||||
-rw-r--r-- | src/backend/commands/vacuum.c | 26 | ||||
-rw-r--r-- | src/backend/executor/execMain.c | 13 | ||||
-rw-r--r-- | src/backend/tcop/utility.c | 26 | ||||
-rw-r--r-- | src/backend/utils/adt/ri_triggers.c | 24 | ||||
-rw-r--r-- | src/backend/utils/fmgr/fmgr.c | 11 | ||||
-rw-r--r-- | src/backend/utils/init/miscinit.c | 93 | ||||
-rw-r--r-- | src/backend/utils/misc/guc.c | 119 | ||||
-rw-r--r-- | src/include/miscadmin.h | 11 | ||||
-rw-r--r-- | src/include/utils/guc.h | 6 | ||||
-rw-r--r-- | src/include/utils/guc_tables.h | 4 |
15 files changed, 323 insertions, 122 deletions
diff --git a/src/backend/access/transam/xact.c b/src/backend/access/transam/xact.c index d2ec35a7bae..b2e32d699fb 100644 --- a/src/backend/access/transam/xact.c +++ b/src/backend/access/transam/xact.c @@ -10,7 +10,7 @@ * * * IDENTIFICATION - * $PostgreSQL: pgsql/src/backend/access/transam/xact.c,v 1.195.4.4 2008/01/03 21:25:00 tgl Exp $ + * $PostgreSQL: pgsql/src/backend/access/transam/xact.c,v 1.195.4.5 2009/12/09 21:58:54 tgl Exp $ * *------------------------------------------------------------------------- */ @@ -112,13 +112,14 @@ typedef struct TransactionStateData int savepointLevel; /* savepoint level */ TransState state; /* low-level state */ TBlockState blockState; /* high-level state */ - int nestingLevel; /* nest depth */ + int nestingLevel; /* transaction nesting depth */ + int gucNestLevel; /* GUC context nesting depth */ MemoryContext curTransactionContext; /* my xact-lifetime * context */ ResourceOwner curTransactionOwner; /* my query resources */ List *childXids; /* subcommitted child XIDs */ AclId prevUser; /* previous CurrentUserId setting */ - bool prevSecDefCxt; /* previous SecurityDefinerContext setting */ + int prevSecContext; /* previous SecurityRestrictionContext */ bool prevXactReadOnly; /* entry-time xact r/o state */ struct TransactionStateData *parent; /* back link to parent */ } TransactionStateData; @@ -146,12 +147,13 @@ static TransactionStateData TopTransactionStateData = { TRANS_DEFAULT, /* transaction state */ TBLOCK_DEFAULT, /* transaction block state from the client * perspective */ - 0, /* nesting level */ + 0, /* transaction nesting depth */ + 0, /* GUC context nesting depth */ NULL, /* cur transaction context */ NULL, /* cur transaction resource owner */ NIL, /* subcommitted child Xids */ 0, /* previous CurrentUserId setting */ - false, /* previous SecurityDefinerContext setting */ + 0, /* previous SecurityRestrictionContext */ false, /* entry-time xact r/o state */ NULL /* link to parent state block */ }; @@ -1396,14 +1398,16 @@ StartTransaction(void) * note: prevXactReadOnly is not used at the outermost level */ s->nestingLevel = 1; + s->gucNestLevel = 1; s->childXids = NIL; - GetUserIdAndContext(&s->prevUser, &s->prevSecDefCxt); - /* SecurityDefinerContext should never be set outside a transaction */ - Assert(!s->prevSecDefCxt); + GetUserIdAndSecContext(&s->prevUser, &s->prevSecContext); + /* SecurityRestrictionContext should never be set outside a transaction */ + Assert(s->prevSecContext == 0); /* * initialize other subsystems for new transaction */ + AtStart_GUC(); AtStart_Inval(); AtStart_Cache(); AfterTriggerBeginXact(); @@ -1571,7 +1575,7 @@ CommitTransaction(void) RESOURCE_RELEASE_AFTER_LOCKS, true, true); - AtEOXact_GUC(true, false); + AtEOXact_GUC(true, 1); AtEOXact_SPI(true); AtEOXact_on_commit_actions(true); AtEOXact_Namespace(true); @@ -1591,6 +1595,7 @@ CommitTransaction(void) s->transactionId = InvalidTransactionId; s->subTransactionId = InvalidSubTransactionId; s->nestingLevel = 0; + s->gucNestLevel = 0; s->childXids = NIL; /* @@ -1653,13 +1658,13 @@ AbortTransaction(void) * Reset user ID which might have been changed transiently. We need this * to clean up in case control escaped out of a SECURITY DEFINER function * or other local change of CurrentUserId; therefore, the prior value - * of SecurityDefinerContext also needs to be restored. + * of SecurityRestrictionContext also needs to be restored. * * (Note: it is not necessary to restore session authorization * setting here because that can only be changed via GUC, and GUC will * take care of rolling it back if need be.) */ - SetUserIdAndContext(s->prevUser, s->prevSecDefCxt); + SetUserIdAndSecContext(s->prevUser, s->prevSecContext); /* * do abort processing @@ -1712,7 +1717,7 @@ AbortTransaction(void) RESOURCE_RELEASE_AFTER_LOCKS, false, true); - AtEOXact_GUC(false, false); + AtEOXact_GUC(false, 1); AtEOXact_SPI(false); AtEOXact_on_commit_actions(false); AtEOXact_Namespace(false); @@ -1759,6 +1764,7 @@ CleanupTransaction(void) s->transactionId = InvalidTransactionId; s->subTransactionId = InvalidSubTransactionId; s->nestingLevel = 0; + s->gucNestLevel = 0; s->childXids = NIL; /* @@ -3322,7 +3328,7 @@ CommitSubTransaction(void) RESOURCE_RELEASE_AFTER_LOCKS, true, false); - AtEOXact_GUC(true, true); + AtEOXact_GUC(true, s->gucNestLevel); AtEOSubXact_SPI(true, s->subTransactionId); AtEOSubXact_on_commit_actions(true, s->subTransactionId, s->parent->subTransactionId); @@ -3395,7 +3401,7 @@ AbortSubTransaction(void) * Reset user ID which might have been changed transiently. (See notes * in AbortTransaction.) */ - SetUserIdAndContext(s->prevUser, s->prevSecDefCxt); + SetUserIdAndSecContext(s->prevUser, s->prevSecContext); /* * We can skip all this stuff if the subxact failed before creating @@ -3438,7 +3444,7 @@ AbortSubTransaction(void) RESOURCE_RELEASE_AFTER_LOCKS, false, false); - AtEOXact_GUC(false, true); + AtEOXact_GUC(false, s->gucNestLevel); AtEOSubXact_SPI(false, s->subTransactionId); AtEOSubXact_on_commit_actions(false, s->subTransactionId, s->parent->subTransactionId); @@ -3530,10 +3536,11 @@ PushTransaction(void) s->subTransactionId = currentSubTransactionId; s->parent = p; s->nestingLevel = p->nestingLevel + 1; + s->gucNestLevel = NewGUCNestLevel(); s->savepointLevel = p->savepointLevel; s->state = TRANS_DEFAULT; s->blockState = TBLOCK_SUBBEGIN; - GetUserIdAndContext(&s->prevUser, &s->prevSecDefCxt); + GetUserIdAndSecContext(&s->prevUser, &s->prevSecContext); s->prevXactReadOnly = XactReadOnly; CurrentTransactionState = s; diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 8b7b0bf1e5d..cf6d81b9f9e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $PostgreSQL: pgsql/src/backend/catalog/index.c,v 1.244.4.4 2008/05/27 21:13:50 tgl Exp $ + * $PostgreSQL: pgsql/src/backend/catalog/index.c,v 1.244.4.5 2009/12/09 21:58:54 tgl Exp $ * * * INTERFACE ROUTINES @@ -46,6 +46,7 @@ #include "storage/smgr.h" #include "utils/builtins.h" #include "utils/fmgroids.h" +#include "utils/guc.h" #include "utils/inval.h" #include "utils/lsyscache.h" #include "utils/relcache.h" @@ -1326,7 +1327,8 @@ index_build(Relation heapRelation, { RegProcedure procedure; AclId save_userid; - bool save_secdefcxt; + int save_sec_context; + int save_nestlevel; /* * sanity checks @@ -1338,11 +1340,14 @@ index_build(Relation heapRelation, Assert(RegProcedureIsValid(procedure)); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. + * Switch to the table owner's userid, so that any index functions are run + * as that user. Also lock down security-restricted operations and + * arrange to make GUC variable changes local to this command. */ - GetUserIdAndContext(&save_userid, &save_secdefcxt); - SetUserIdAndContext(heapRelation->rd_rel->relowner, true); + GetUserIdAndSecContext(&save_userid, &save_sec_context); + SetUserIdAndSecContext(heapRelation->rd_rel->relowner, + save_sec_context | SECURITY_RESTRICTED_OPERATION); + save_nestlevel = NewGUCNestLevel(); /* * Call the access method's build procedure @@ -1352,8 +1357,11 @@ index_build(Relation heapRelation, PointerGetDatum(indexRelation), PointerGetDatum(indexInfo)); - /* Restore userid */ - SetUserIdAndContext(save_userid, save_secdefcxt); + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, save_nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(save_userid, save_sec_context); } diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index 91a0cc05b35..5eaf7a2ecf9 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $PostgreSQL: pgsql/src/backend/commands/analyze.c,v 1.80.4.1 2008/01/03 21:25:00 tgl Exp $ + * $PostgreSQL: pgsql/src/backend/commands/analyze.c,v 1.80.4.2 2009/12/09 21:58:54 tgl Exp $ * *------------------------------------------------------------------------- */ @@ -34,6 +34,7 @@ #include "utils/builtins.h" #include "utils/datum.h" #include "utils/fmgroids.h" +#include "utils/guc.h" #include "utils/lsyscache.h" #include "utils/syscache.h" #include "utils/tuplesort.h" @@ -111,7 +112,8 @@ analyze_rel(Oid relid, VacuumStmt *vacstmt) double totalrows; HeapTuple *rows; AclId save_userid; - bool save_secdefcxt; + int save_sec_context; + int save_nestlevel; if (vacstmt->verbose) elevel = INFO; @@ -202,11 +204,14 @@ analyze_rel(Oid relid, VacuumStmt *vacstmt) RelationGetRelationName(onerel)))); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. + * Switch to the table owner's userid, so that any index functions are run + * as that user. Also lock down security-restricted operations and + * arrange to make GUC variable changes local to this command. */ - GetUserIdAndContext(&save_userid, &save_secdefcxt); - SetUserIdAndContext(onerel->rd_rel->relowner, true); + GetUserIdAndSecContext(&save_userid, &save_sec_context); + SetUserIdAndSecContext(onerel->rd_rel->relowner, + save_sec_context | SECURITY_RESTRICTED_OPERATION); + save_nestlevel = NewGUCNestLevel(); /* * Determine which columns to analyze @@ -444,8 +449,11 @@ cleanup: */ relation_close(onerel, NoLock); - /* Restore userid */ - SetUserIdAndContext(save_userid, save_secdefcxt); + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, save_nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(save_userid, save_sec_context); } /* diff --git a/src/backend/commands/schemacmds.c b/src/backend/commands/schemacmds.c index 49e931013a5..d255e3a5cb2 100644 --- a/src/backend/commands/schemacmds.c +++ b/src/backend/commands/schemacmds.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $PostgreSQL: pgsql/src/backend/commands/schemacmds.c,v 1.27.4.1 2008/01/03 21:25:00 tgl Exp $ + * $PostgreSQL: pgsql/src/backend/commands/schemacmds.c,v 1.27.4.2 2009/12/09 21:58:54 tgl Exp $ * *------------------------------------------------------------------------- */ @@ -46,10 +46,10 @@ CreateSchemaCommand(CreateSchemaStmt *stmt) const char *owner_name; AclId owner_userid; AclId saved_userid; - bool saved_secdefcxt; + int save_sec_context; AclResult aclresult; - GetUserIdAndContext(&saved_userid, &saved_secdefcxt); + GetUserIdAndSecContext(&saved_userid, &save_sec_context); /* * Figure out user identities. @@ -72,7 +72,8 @@ CreateSchemaCommand(CreateSchemaStmt *stmt) * (This will revert to session user on error or at the end of * this routine.) */ - SetUserIdAndContext(owner_userid, true); + SetUserIdAndSecContext(owner_userid, + save_sec_context | SECURITY_LOCAL_USERID_CHANGE); } else { @@ -151,8 +152,8 @@ CreateSchemaCommand(CreateSchemaStmt *stmt) /* Reset search path to normal state */ PopSpecialNamespace(namespaceId); - /* Reset current user */ - SetUserIdAndContext(saved_userid, saved_secdefcxt); + /* Reset current user and security context */ + SetUserIdAndSecContext(saved_userid, save_sec_context); } diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 8001b0798c4..3c1cbae6955 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $PostgreSQL: pgsql/src/backend/commands/tablecmds.c,v 1.142.4.10 2008/05/27 21:13:50 tgl Exp $ + * $PostgreSQL: pgsql/src/backend/commands/tablecmds.c,v 1.142.4.11 2009/12/09 21:58:54 tgl Exp $ * *------------------------------------------------------------------------- */ @@ -296,6 +296,16 @@ DefineRelation(CreateStmt *stmt, char relkind) errmsg("ON COMMIT can only be used on temporary tables"))); /* + * Security check: disallow creating temp tables from security-restricted + * code. This is needed because calling code might not expect untrusted + * tables to appear in pg_temp at the front of its search path. + */ + if (stmt->relation->istemp && InSecurityRestrictedOperation()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("cannot create temporary table within security-restricted operation"))); + + /* * Look up the namespace in which we are supposed to create the * relation. Check we have permission to create there. Skip check if * bootstrapping, since permissions machinery may not be working yet. diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index dc481f30f5f..ccef7141092 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -13,7 +13,7 @@ * * * IDENTIFICATION - * $PostgreSQL: pgsql/src/backend/commands/vacuum.c,v 1.299.4.5 2009/11/10 18:01:26 alvherre Exp $ + * $PostgreSQL: pgsql/src/backend/commands/vacuum.c,v 1.299.4.6 2009/12/09 21:58:55 tgl Exp $ * *------------------------------------------------------------------------- */ @@ -43,6 +43,7 @@ #include "utils/acl.h" #include "utils/builtins.h" #include "utils/fmgroids.h" +#include "utils/guc.h" #include "utils/inval.h" #include "utils/lsyscache.h" #include "utils/relcache.h" @@ -884,7 +885,8 @@ vacuum_rel(Oid relid, VacuumStmt *vacstmt, char expected_relkind) Oid toast_relid; bool result; AclId save_userid; - bool save_secdefcxt; + int save_sec_context; + int save_nestlevel; bool heldoff; /* Begin a transaction for vacuuming this relation */ @@ -1001,12 +1003,15 @@ vacuum_rel(Oid relid, VacuumStmt *vacstmt, char expected_relkind) toast_relid = onerel->rd_rel->reltoastrelid; /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. (This is unnecessary, but harmless, for lazy - * VACUUM.) + * Switch to the table owner's userid, so that any index functions are run + * as that user. Also lock down security-restricted operations and + * arrange to make GUC variable changes local to this command. + * (This is unnecessary, but harmless, for lazy VACUUM.) */ - GetUserIdAndContext(&save_userid, &save_secdefcxt); - SetUserIdAndContext(onerel->rd_rel->relowner, true); + GetUserIdAndSecContext(&save_userid, &save_sec_context); + SetUserIdAndSecContext(onerel->rd_rel->relowner, + save_sec_context | SECURITY_RESTRICTED_OPERATION); + save_nestlevel = NewGUCNestLevel(); /* * Do the actual work --- either FULL or "lazy" vacuum @@ -1018,8 +1023,11 @@ vacuum_rel(Oid relid, VacuumStmt *vacstmt, char expected_relkind) result = true; /* did the vacuum */ - /* Restore userid */ - SetUserIdAndContext(save_userid, save_secdefcxt); + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, save_nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(save_userid, save_sec_context); /* all done with this class, but hold lock until commit */ relation_close(onerel, NoLock); diff --git a/src/backend/executor/execMain.c b/src/backend/executor/execMain.c index 267a86189c5..78edc58e8b6 100644 --- a/src/backend/executor/execMain.c +++ b/src/backend/executor/execMain.c @@ -26,7 +26,7 @@ * * * IDENTIFICATION - * $PostgreSQL: pgsql/src/backend/executor/execMain.c,v 1.241.4.4 2008/08/08 17:01:41 tgl Exp $ + * $PostgreSQL: pgsql/src/backend/executor/execMain.c,v 1.241.4.5 2009/12/09 21:58:55 tgl Exp $ * *------------------------------------------------------------------------- */ @@ -758,6 +758,17 @@ InitPlan(QueryDesc *queryDesc, bool explainOnly) TupleDesc tupdesc; /* + * Security check: disallow creating temp tables from + * security-restricted code. This is needed because calling code + * might not expect untrusted tables to appear in pg_temp at the front + * of its search path. + */ + if (parseTree->into->istemp && InSecurityRestrictedOperation()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("cannot create temporary table within security-restricted operation"))); + + /* * find namespace to create in, check permissions */ intoName = parseTree->into->relname; diff --git a/src/backend/tcop/utility.c b/src/backend/tcop/utility.c index 976a22c8ee1..e51e51ae9f6 100644 --- a/src/backend/tcop/utility.c +++ b/src/backend/tcop/utility.c @@ -10,7 +10,7 @@ * * * IDENTIFICATION - * $PostgreSQL: pgsql/src/backend/tcop/utility.c,v 1.231.4.1 2005/01/24 17:46:29 tgl Exp $ + * $PostgreSQL: pgsql/src/backend/tcop/utility.c,v 1.231.4.2 2009/12/09 21:58:55 tgl Exp $ * *------------------------------------------------------------------------- */ @@ -330,6 +330,25 @@ check_xact_readonly(Node *parsetree) /* + * CheckRestrictedOperation: throw error for hazardous command if we're + * inside a security restriction context. + * + * This is needed to protect session-local state for which there is not any + * better-defined protection mechanism, such as ownership. + */ +static void +CheckRestrictedOperation(const char *cmdname) +{ + if (InSecurityRestrictedOperation()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + /* translator: %s is name of a SQL command, eg PREPARE */ + errmsg("cannot execute %s within security-restricted operation", + cmdname))); +} + + +/* * ProcessUtility * general utility function invoker * @@ -454,6 +473,7 @@ ProcessUtility(Node *parsetree, { ClosePortalStmt *stmt = (ClosePortalStmt *) parsetree; + CheckRestrictedOperation("CLOSE"); PerformPortalClose(stmt->portalname); } break; @@ -588,6 +608,7 @@ ProcessUtility(Node *parsetree, break; case T_PrepareStmt: + CheckRestrictedOperation("PREPARE"); PrepareQuery((PrepareStmt *) parsetree); break; @@ -596,6 +617,7 @@ ProcessUtility(Node *parsetree, break; case T_DeallocateStmt: + CheckRestrictedOperation("DEALLOCATE"); DeallocateQuery((DeallocateStmt *) parsetree); break; @@ -787,6 +809,7 @@ ProcessUtility(Node *parsetree, { ListenStmt *stmt = (ListenStmt *) parsetree; + CheckRestrictedOperation("LISTEN"); Async_Listen(stmt->relation->relname, MyProcPid); } break; @@ -795,6 +818,7 @@ ProcessUtility(Node *parsetree, { UnlistenStmt *stmt = (UnlistenStmt *) parsetree; + CheckRestrictedOperation("UNLISTEN"); Async_Unlisten(stmt->relation->relname, MyProcPid); } break; diff --git a/src/backend/utils/adt/ri_triggers.c b/src/backend/utils/adt/ri_triggers.c index 32925146f92..d614c732923 100644 --- a/src/backend/utils/adt/ri_triggers.c +++ b/src/backend/utils/adt/ri_triggers.c @@ -17,7 +17,7 @@ * * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group * - * $PostgreSQL: pgsql/src/backend/utils/adt/ri_triggers.c,v 1.76.4.3 2008/01/03 21:25:00 tgl Exp $ + * $PostgreSQL: pgsql/src/backend/utils/adt/ri_triggers.c,v 1.76.4.4 2009/12/09 21:58:55 tgl Exp $ * * ---------- */ @@ -3001,7 +3001,7 @@ ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, void *qplan; Relation query_rel; AclId save_userid; - bool save_secdefcxt; + int save_sec_context; /* * The query is always run against the FK table except when this is an @@ -3015,8 +3015,9 @@ ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, query_rel = fk_rel; /* Switch to proper UID to perform check as */ - GetUserIdAndContext(&save_userid, &save_secdefcxt); - SetUserIdAndContext(RelationGetForm(query_rel)->relowner, true); + GetUserIdAndSecContext(&save_userid, &save_sec_context); + SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner, + save_sec_context | SECURITY_LOCAL_USERID_CHANGE); /* Create the plan */ qplan = SPI_prepare(querystr, nargs, argtypes); @@ -3024,8 +3025,8 @@ ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, if (qplan == NULL) elog(ERROR, "SPI_prepare returned %d for %s", SPI_result, querystr); - /* Restore UID */ - SetUserIdAndContext(save_userid, save_secdefcxt); + /* Restore UID and security context */ + SetUserIdAndSecContext(save_userid, save_sec_context); /* Save the plan if requested */ if (cache_plan) @@ -3055,7 +3056,7 @@ ri_PerformCheck(RI_QueryKey *qkey, void *qplan, int limit; int spi_result; AclId save_userid; - bool save_secdefcxt; + int save_sec_context; Datum vals[RI_MAX_NUMKEYS * 2]; char nulls[RI_MAX_NUMKEYS * 2]; @@ -3134,8 +3135,9 @@ ri_PerformCheck(RI_QueryKey *qkey, void *qplan, limit = (expect_OK == SPI_OK_SELECT) ? 1 : 0; /* Switch to proper UID to perform check as */ - GetUserIdAndContext(&save_userid, &save_secdefcxt); - SetUserIdAndContext(RelationGetForm(query_rel)->relowner, true); + GetUserIdAndSecContext(&save_userid, &save_sec_context); + SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner, + save_sec_context | SECURITY_LOCAL_USERID_CHANGE); /* Finally we can run the query. */ spi_result = SPI_execute_snapshot(qplan, @@ -3143,8 +3145,8 @@ ri_PerformCheck(RI_QueryKey *qkey, void *qplan, test_snapshot, crosscheck_snapshot, false, false, limit); - /* Restore UID */ - SetUserIdAndContext(save_userid, save_secdefcxt); + /* Restore UID and security context */ + SetUserIdAndSecContext(save_userid, save_sec_context); /* Check result */ if (spi_result < 0) diff --git a/src/backend/utils/fmgr/fmgr.c b/src/backend/utils/fmgr/fmgr.c index bd8a59a0a5c..46aed404e82 100644 --- a/src/backend/utils/fmgr/fmgr.c +++ b/src/backend/utils/fmgr/fmgr.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $PostgreSQL: pgsql/src/backend/utils/fmgr/fmgr.c,v 1.88.4.3 2008/01/03 21:25:00 tgl Exp $ + * $PostgreSQL: pgsql/src/backend/utils/fmgr/fmgr.c,v 1.88.4.4 2009/12/09 21:58:55 tgl Exp $ * *------------------------------------------------------------------------- */ @@ -791,7 +791,7 @@ fmgr_security_definer(PG_FUNCTION_ARGS) FmgrInfo *save_flinfo; struct fmgr_security_definer_cache * volatile fcache; AclId save_userid; - bool save_secdefcxt; + int save_sec_context; HeapTuple tuple; if (!fcinfo->flinfo->fn_extra) @@ -817,8 +817,9 @@ fmgr_security_definer(PG_FUNCTION_ARGS) else fcache = fcinfo->flinfo->fn_extra; - GetUserIdAndContext(&save_userid, &save_secdefcxt); - SetUserIdAndContext(fcache->userid, true); + GetUserIdAndSecContext(&save_userid, &save_sec_context); + SetUserIdAndSecContext(fcache->userid, + save_sec_context | SECURITY_LOCAL_USERID_CHANGE); /* * We don't need to restore the userid settings on error, because the @@ -842,7 +843,7 @@ fmgr_security_definer(PG_FUNCTION_ARGS) fcinfo->flinfo = save_flinfo; - SetUserIdAndContext(save_userid, save_secdefcxt); + SetUserIdAndSecContext(save_userid, save_sec_context); return result; } diff --git a/src/backend/utils/init/miscinit.c b/src/backend/utils/init/miscinit.c index 4db647b9ff9..eb98c95c158 100644 --- a/src/backend/utils/init/miscinit.c +++ b/src/backend/utils/init/miscinit.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $PostgreSQL: pgsql/src/backend/utils/init/miscinit.c,v 1.137.4.2 2008/01/03 21:25:00 tgl Exp $ + * $PostgreSQL: pgsql/src/backend/utils/init/miscinit.c,v 1.137.4.3 2009/12/09 21:58:55 tgl Exp $ * *------------------------------------------------------------------------- */ @@ -261,8 +261,10 @@ make_absolute_path(const char *path) * is the session user. You are yourself responsible to save and * restore the current user id if you need to change it. * - * SecurityDefinerContext is TRUE if we are within a SECURITY DEFINER function - * or another context that temporarily changes CurrentUserId. + * SecurityRestrictionContext holds flags indicating reason(s) for changing + * CurrentUserId. In some cases we need to lock down operations that are + * not directly controlled by privilege settings, and this provides a + * convenient way to do it. * ---------------------------------------------------------------- */ static AclId AuthenticatedUserId = 0; @@ -271,13 +273,13 @@ static AclId CurrentUserId = 0; static bool AuthenticatedUserIsSuperuser = false; -static bool SecurityDefinerContext = false; +static int SecurityRestrictionContext = 0; /* * GetUserId - get the current effective user ID. * - * Note: there's no SetUserId() anymore; use SetUserIdAndContext(). + * Note: there's no SetUserId() anymore; use SetUserIdAndSecContext(). */ AclId GetUserId(void) @@ -301,7 +303,7 @@ GetSessionUserId(void) static void SetSessionUserId(AclId newid) { - AssertState(!SecurityDefinerContext); + AssertState(SecurityRestrictionContext == 0); AssertArg(AclIdIsValid(newid)); SessionUserId = newid; CurrentUserId = newid; @@ -309,11 +311,29 @@ SetSessionUserId(AclId newid) /* - * GetUserIdAndContext/SetUserIdAndContext - get/set the current user ID - * and the SecurityDefinerContext flag. + * GetUserIdAndSecContext/SetUserIdAndSecContext - get/set the current user ID + * and the SecurityRestrictionContext flags. * - * Unlike GetUserId, GetUserIdAndContext does *not* Assert that the current - * value of CurrentUserId is valid; nor does SetUserIdAndContext require + * Currently there are two valid bits in SecurityRestrictionContext: + * + * SECURITY_LOCAL_USERID_CHANGE indicates that we are inside an operation + * that is temporarily changing CurrentUserId via these functions. This is + * needed to indicate that the actual value of CurrentUserId is not in sync + * with guc.c's internal state, so SET ROLE has to be disallowed. + * + * SECURITY_RESTRICTED_OPERATION indicates that we are inside an operation + * that does not wish to trust called user-defined functions at all. This + * bit prevents not only SET ROLE, but various other changes of session state + * that normally is unprotected but might possibly be used to subvert the + * calling session later. An example is replacing an existing prepared + * statement with new code, which will then be executed with the outer + * session's permissions when the prepared statement is next used. Since + * these restrictions are fairly draconian, we apply them only in contexts + * where the called functions are really supposed to be side-effect-free + * anyway, such as VACUUM/ANALYZE/REINDEX. + * + * Unlike GetUserId, GetUserIdAndSecContext does *not* Assert that the current + * value of CurrentUserId is valid; nor does SetUserIdAndSecContext require * the new value to be valid. In fact, these routines had better not * ever throw any kind of error. This is because they are used by * StartTransaction and AbortTransaction to save/restore the settings, @@ -322,27 +342,66 @@ SetSessionUserId(AclId newid) * through AbortTransaction without asserting in case InitPostgres fails. */ void -GetUserIdAndContext(AclId *userid, bool *sec_def_context) +GetUserIdAndSecContext(AclId *userid, int *sec_context) { *userid = CurrentUserId; - *sec_def_context = SecurityDefinerContext; + *sec_context = SecurityRestrictionContext; } void -SetUserIdAndContext(AclId userid, bool sec_def_context) +SetUserIdAndSecContext(AclId userid, int sec_context) { CurrentUserId = userid; - SecurityDefinerContext = sec_def_context; + SecurityRestrictionContext = sec_context; } /* - * InSecurityDefinerContext - are we inside a SECURITY DEFINER context? + * InLocalUserIdChange - are we inside a local change of CurrentUserId? */ bool -InSecurityDefinerContext(void) +InLocalUserIdChange(void) { - return SecurityDefinerContext; + return (SecurityRestrictionContext & SECURITY_LOCAL_USERID_CHANGE) != 0; +} + +/* + * InSecurityRestrictedOperation - are we inside a security-restricted command? + */ +bool +InSecurityRestrictedOperation(void) +{ + return (SecurityRestrictionContext & SECURITY_RESTRICTED_OPERATION) != 0; +} + + +/* + * These are obsolete versions of Get/SetUserIdAndSecContext that are + * only provided for bug-compatibility with some rather dubious code in + * pljava. We allow the userid to be set, but only when not inside a + * security restriction context. + */ +void +GetUserIdAndContext(AclId *userid, bool *sec_def_context) +{ + *userid = CurrentUserId; + *sec_def_context = InLocalUserIdChange(); +} + +void +SetUserIdAndContext(AclId userid, bool sec_def_context) +{ + /* We throw the same error SET ROLE would. */ + if (InSecurityRestrictedOperation()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("cannot set parameter \"%s\" within security-restricted operation", + "role"))); + CurrentUserId = userid; + if (sec_def_context) + SecurityRestrictionContext |= SECURITY_LOCAL_USERID_CHANGE; + else + SecurityRestrictionContext &= ~SECURITY_LOCAL_USERID_CHANGE; } diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c index 6b612fb5313..06b7f54e887 100644 --- a/src/backend/utils/misc/guc.c +++ b/src/backend/utils/misc/guc.c @@ -10,7 +10,7 @@ * Written by Peter Eisentraut <peter_e@gmx.net>. * * IDENTIFICATION - * $PostgreSQL: pgsql/src/backend/utils/misc/guc.c,v 1.252.4.6 2009/09/03 22:08:54 tgl Exp $ + * $PostgreSQL: pgsql/src/backend/utils/misc/guc.c,v 1.252.4.7 2009/12/09 21:58:55 tgl Exp $ * *-------------------------------------------------------------------- */ @@ -1682,7 +1682,7 @@ static struct config_string ConfigureNamesString[] = {"session_authorization", PGC_USERSET, UNGROUPED, gettext_noop("Sets the session user name."), NULL, - GUC_IS_NAME | GUC_REPORT | GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE | GUC_NOT_WHILE_SEC_DEF + GUC_IS_NAME | GUC_REPORT | GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE | GUC_NOT_WHILE_SEC_REST }, &session_authorization_string, NULL, assign_session_authorization, show_session_authorization @@ -1899,6 +1899,8 @@ static bool reporting_enabled; /* TRUE to enable GUC_REPORT */ static char *guc_string_workspace; /* for avoiding memory leaks */ +static int GUCNestLevel = 0; /* 1 when in main transaction */ + static int guc_var_compare(const void *a, const void *b); static int guc_name_compare(const char *namea, const char *nameb); @@ -2739,17 +2741,16 @@ ResetAllOptions(void) static void push_old_value(struct config_generic * gconf) { - int my_level = GetCurrentTransactionNestLevel(); GucStack *stack; /* If we're not inside a transaction, do nothing */ - if (my_level == 0) + if (GUCNestLevel == 0) return; for (;;) { /* Done if we already pushed it at this nesting depth */ - if (gconf->stack && gconf->stack->nest_level >= my_level) + if (gconf->stack && gconf->stack->nest_level >= GUCNestLevel) return; /* @@ -2808,17 +2809,53 @@ push_old_value(struct config_generic * gconf) } /* - * Do GUC processing at transaction or subtransaction commit or abort. + * Do GUC processing at main transaction start. + */ +void +AtStart_GUC(void) +{ + /* + * The nest level should be 0 between transactions; if it isn't, + * somebody didn't call AtEOXact_GUC, or called it with the wrong + * nestLevel. We throw a warning but make no other effort to clean up. + */ + if (GUCNestLevel != 0) + elog(WARNING, "GUC nest level = %d at transaction start", + GUCNestLevel); + GUCNestLevel = 1; +} + +/* + * Enter a new nesting level for GUC values. This is called at subtransaction + * start and when entering a function that has proconfig settings. NOTE that + * we must not risk error here, else subtransaction start will be unhappy. + */ +int +NewGUCNestLevel(void) +{ + return ++GUCNestLevel; +} + +/* + * Do GUC processing at transaction or subtransaction commit or abort, or + * when exiting a function that has proconfig settings. (The name is thus + * a bit of a misnomer; perhaps it should be ExitGUCNestLevel or some such.) + * During abort, we discard all GUC settings that were applied at nesting + * levels >= nestLevel. nestLevel == 1 corresponds to the main transaction. */ void -AtEOXact_GUC(bool isCommit, bool isSubXact) +AtEOXact_GUC(bool isCommit, int nestLevel) { - int my_level; int i; + Assert(nestLevel > 0 && nestLevel <= GUCNestLevel); + /* Quick exit if nothing's changed in this transaction */ if (!guc_dirty) + { + GUCNestLevel = nestLevel - 1; return; + } /* Prevent memory leak if ereport during an assign_hook */ if (guc_string_workspace) @@ -2827,9 +2864,6 @@ AtEOXact_GUC(bool isCommit, bool isSubXact) guc_string_workspace = NULL; } - my_level = GetCurrentTransactionNestLevel(); - Assert(isSubXact ? (my_level > 1) : (my_level == 1)); - for (i = 0; i < num_guc_variables; i++) { struct config_generic *gconf = guc_variables[i]; @@ -2849,9 +2883,9 @@ AtEOXact_GUC(bool isCommit, bool isSubXact) /* Assert that we stacked old value before changing it */ Assert(stack != NULL && (my_status & GUC_HAVE_STACK)); /* However, the last change may have been at an outer xact level */ - if (stack->nest_level < my_level) + if (stack->nest_level < nestLevel) continue; - Assert(stack->nest_level == my_level); + Assert(stack->nest_level == nestLevel); /* * We will pop the stack entry. Start by restoring outer xact @@ -3036,7 +3070,7 @@ AtEOXact_GUC(bool isCommit, bool isSubXact) set_string_field(conf, &stack->tentative_val.stringval, NULL); /* Don't store tentative value separately after commit */ - if (!isSubXact) + if (nestLevel == 1) set_string_field(conf, &conf->tentative_val, NULL); break; } @@ -3050,7 +3084,7 @@ AtEOXact_GUC(bool isCommit, bool isSubXact) * If we're now out of all xact levels, forget TENTATIVE status * bit; there's nothing tentative about the value anymore. */ - if (!isSubXact) + if (nestLevel == 1) { Assert(gconf->stack == NULL); gconf->status = 0; @@ -3067,8 +3101,11 @@ AtEOXact_GUC(bool isCommit, bool isSubXact) * know that all outer transaction levels will have stacked values to * deal with.) */ - if (!isSubXact) + if (nestLevel == 1) guc_dirty = false; + + /* Update nesting level */ + GUCNestLevel = nestLevel - 1; } @@ -3375,29 +3412,45 @@ set_config_option(const char *name, const char *value, } /* - * Disallow changing GUC_NOT_WHILE_SEC_DEF values if we are inside a - * security-definer function. We can reject this regardless of - * the context or source, mainly because sources that it might be + * Disallow changing GUC_NOT_WHILE_SEC_REST values if we are inside a + * security restriction context. We can reject this regardless of + * the GUC context or source, mainly because sources that it might be * reasonable to override for won't be seen while inside a function. * - * Note: variables marked GUC_NOT_WHILE_SEC_DEF should probably be marked + * Note: variables marked GUC_NOT_WHILE_SEC_REST should usually be marked * GUC_NO_RESET_ALL as well, because ResetAllOptions() doesn't check this. + * An exception might be made if the reset value is assumed to be "safe". * - * Note: this flag is currently used for "session_authorization". - * We need to prohibit this because when we exit the sec-def - * context, GUC won't be notified, leaving things out of sync. - * - * XXX it would be nice to allow these cases in future, with the behavior - * being that the SET's effects end when the security definer context is - * exited. + * Note: this flag is currently used for "session_authorization" and + * "role". We need to prohibit changing these inside a local userid + * context because when we exit it, GUC won't be notified, leaving things + * out of sync. (This could be fixed by forcing a new GUC nesting level, + * but that would change behavior in possibly-undesirable ways.) Also, + * we prohibit changing these in a security-restricted operation because + * otherwise RESET could be used to regain the session user's privileges. */ - if ((record->flags & GUC_NOT_WHILE_SEC_DEF) && InSecurityDefinerContext()) + if (record->flags & GUC_NOT_WHILE_SEC_REST) { - ereport(elevel, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("cannot set parameter \"%s\" within security-definer function", - name))); - return false; + if (InLocalUserIdChange()) + { + /* + * Phrasing of this error message is historical, but it's the + * most common case. + */ + ereport(elevel, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("cannot set parameter \"%s\" within security-definer function", + name))); + return false; + } + if (InSecurityRestrictedOperation()) + { + ereport(elevel, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("cannot set parameter \"%s\" within security-restricted operation", + name))); + return false; + } } /* diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h index bdf8aaa0b11..3d6c62cbf82 100644 --- a/src/include/miscadmin.h +++ b/src/include/miscadmin.h @@ -13,7 +13,7 @@ * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $PostgreSQL: pgsql/src/include/miscadmin.h,v 1.174.4.1 2008/01/03 21:25:00 tgl Exp $ + * $PostgreSQL: pgsql/src/include/miscadmin.h,v 1.174.4.2 2009/12/09 21:58:56 tgl Exp $ * * NOTES * some of the information in this file should be moved to other files. @@ -223,6 +223,10 @@ extern void check_stack_depth(void); * POSTGRES directory path definitions. * *****************************************************************************/ +/* flags to be OR'd to form sec_context */ +#define SECURITY_LOCAL_USERID_CHANGE 0x0001 +#define SECURITY_RESTRICTED_OPERATION 0x0002 + extern char *DatabasePath; /* in utils/misc/database.c */ @@ -234,9 +238,12 @@ extern void SetDatabasePath(const char *path); extern char *GetUserNameFromId(AclId userid); extern AclId GetUserId(void); extern AclId GetSessionUserId(void); +extern void GetUserIdAndSecContext(AclId *userid, int *sec_context); +extern void SetUserIdAndSecContext(AclId userid, int sec_context); +extern bool InLocalUserIdChange(void); +extern bool InSecurityRestrictedOperation(void); extern void GetUserIdAndContext(AclId *userid, bool *sec_def_context); extern void SetUserIdAndContext(AclId userid, bool sec_def_context); -extern bool InSecurityDefinerContext(void); extern void InitializeSessionUserId(const char *username); extern void InitializeSessionUserIdStandalone(void); extern void SetSessionAuthorization(AclId userid, bool is_superuser); diff --git a/src/include/utils/guc.h b/src/include/utils/guc.h index 458cc49172a..18d1dc17dab 100644 --- a/src/include/utils/guc.h +++ b/src/include/utils/guc.h @@ -7,7 +7,7 @@ * Copyright (c) 2000-2005, PostgreSQL Global Development Group * Written by Peter Eisentraut <peter_e@gmx.net>. * - * $PostgreSQL: pgsql/src/include/utils/guc.h,v 1.58.4.1 2005/03/25 16:17:39 tgl Exp $ + * $PostgreSQL: pgsql/src/include/utils/guc.h,v 1.58.4.2 2009/12/09 21:58:56 tgl Exp $ *-------------------------------------------------------------------- */ #ifndef GUC_H @@ -184,7 +184,9 @@ extern void ProcessConfigFile(GucContext context); extern void InitializeGUCOptions(void); extern bool SelectConfigFiles(const char *userDoption, const char *progname); extern void ResetAllOptions(void); -extern void AtEOXact_GUC(bool isCommit, bool isSubXact); +extern void AtStart_GUC(void); +extern int NewGUCNestLevel(void); +extern void AtEOXact_GUC(bool isCommit, int nestLevel); extern void BeginReportingGUCOptions(void); extern void ParseLongOption(const char *string, char **name, char **value); extern bool set_config_option(const char *name, const char *value, diff --git a/src/include/utils/guc_tables.h b/src/include/utils/guc_tables.h index 83bd78b32d4..cd978484a75 100644 --- a/src/include/utils/guc_tables.h +++ b/src/include/utils/guc_tables.h @@ -7,7 +7,7 @@ * * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group * - * $PostgreSQL: pgsql/src/include/utils/guc_tables.h,v 1.19.4.2 2009/09/03 22:08:54 tgl Exp $ + * $PostgreSQL: pgsql/src/include/utils/guc_tables.h,v 1.19.4.3 2009/12/09 21:58:56 tgl Exp $ * *------------------------------------------------------------------------- */ @@ -127,7 +127,7 @@ struct config_generic #define GUC_SUPERUSER_ONLY 0x0100 /* show only to superusers */ #define GUC_IS_NAME 0x0200 /* limit string to NAMEDATALEN-1 */ -#define GUC_NOT_WHILE_SEC_DEF 0x8000 /* can't change inside sec-def func */ +#define GUC_NOT_WHILE_SEC_REST 0x8000 /* can't set if security restricted */ /* bit values in status field */ #define GUC_HAVE_TENTATIVE 0x0001 /* tentative value is defined */ |