PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
user.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * user.c
4  * Commands for manipulating roles (formerly called users).
5  *
6  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * src/backend/commands/user.c
10  *
11  *-------------------------------------------------------------------------
12  */
13 #include "postgres.h"
14 
15 #include "access/genam.h"
16 #include "access/heapam.h"
17 #include "access/htup_details.h"
18 #include "access/xact.h"
19 #include "catalog/binary_upgrade.h"
20 #include "catalog/catalog.h"
21 #include "catalog/dependency.h"
22 #include "catalog/indexing.h"
23 #include "catalog/objectaccess.h"
25 #include "catalog/pg_authid.h"
26 #include "catalog/pg_database.h"
28 #include "commands/comment.h"
29 #include "commands/dbcommands.h"
30 #include "commands/seclabel.h"
31 #include "commands/user.h"
32 #include "libpq/crypt.h"
33 #include "miscadmin.h"
34 #include "storage/lmgr.h"
35 #include "utils/acl.h"
36 #include "utils/builtins.h"
37 #include "utils/fmgroids.h"
38 #include "utils/syscache.h"
39 #include "utils/timestamp.h"
40 #include "utils/tqual.h"
41 
42 /* Potentially set by pg_upgrade_support functions */
44 
45 
46 /* GUC parameter */
48 
49 /* Hook to check passwords in CreateRole() and AlterRole() */
51 
52 static void AddRoleMems(const char *rolename, Oid roleid,
53  List *memberSpecs, List *memberIds,
54  Oid grantorId, bool admin_opt);
55 static void DelRoleMems(const char *rolename, Oid roleid,
56  List *memberSpecs, List *memberIds,
57  bool admin_opt);
58 
59 
60 /* Check if current user has createrole privileges */
61 static bool
63 {
65 }
66 
67 
68 /*
69  * CREATE ROLE
70  */
71 Oid
73 {
74  Relation pg_authid_rel;
75  TupleDesc pg_authid_dsc;
76  HeapTuple tuple;
77  Datum new_record[Natts_pg_authid];
78  bool new_record_nulls[Natts_pg_authid];
79  Oid roleid;
80  ListCell *item;
82  char *password = NULL; /* user password */
83  int password_type = Password_encryption;
84  bool issuper = false; /* Make the user a superuser? */
85  bool inherit = true; /* Auto inherit privileges? */
86  bool createrole = false; /* Can this user create roles? */
87  bool createdb = false; /* Can the user create databases? */
88  bool canlogin = false; /* Can this user login? */
89  bool isreplication = false; /* Is this a replication role? */
90  bool bypassrls = false; /* Is this a row security enabled
91  * role? */
92  int connlimit = -1; /* maximum connections allowed */
93  List *addroleto = NIL; /* roles to make this a member of */
94  List *rolemembers = NIL; /* roles to be members of this role */
95  List *adminmembers = NIL; /* roles to be admins of this role */
96  char *validUntil = NULL; /* time the login is valid until */
97  Datum validUntil_datum; /* same, as timestamptz Datum */
98  bool validUntil_null;
99  DefElem *dpassword = NULL;
100  DefElem *dissuper = NULL;
101  DefElem *dinherit = NULL;
102  DefElem *dcreaterole = NULL;
103  DefElem *dcreatedb = NULL;
104  DefElem *dcanlogin = NULL;
105  DefElem *disreplication = NULL;
106  DefElem *dconnlimit = NULL;
107  DefElem *daddroleto = NULL;
108  DefElem *drolemembers = NULL;
109  DefElem *dadminmembers = NULL;
110  DefElem *dvalidUntil = NULL;
111  DefElem *dbypassRLS = NULL;
112 
113  /* The defaults can vary depending on the original statement type */
114  switch (stmt->stmt_type)
115  {
116  case ROLESTMT_ROLE:
117  break;
118  case ROLESTMT_USER:
119  canlogin = true;
120  /* may eventually want inherit to default to false here */
121  break;
122  case ROLESTMT_GROUP:
123  break;
124  }
125 
126  /* Extract options from the statement node tree */
127  foreach(option, stmt->options)
128  {
129  DefElem *defel = (DefElem *) lfirst(option);
130 
131  if (strcmp(defel->defname, "password") == 0 ||
132  strcmp(defel->defname, "encryptedPassword") == 0 ||
133  strcmp(defel->defname, "unencryptedPassword") == 0)
134  {
135  if (dpassword)
136  ereport(ERROR,
137  (errcode(ERRCODE_SYNTAX_ERROR),
138  errmsg("conflicting or redundant options"),
139  parser_errposition(pstate, defel->location)));
140  dpassword = defel;
141  if (strcmp(defel->defname, "encryptedPassword") == 0)
142  password_type = PASSWORD_TYPE_MD5;
143  else if (strcmp(defel->defname, "unencryptedPassword") == 0)
144  password_type = PASSWORD_TYPE_PLAINTEXT;
145  }
146  else if (strcmp(defel->defname, "sysid") == 0)
147  {
148  ereport(NOTICE,
149  (errmsg("SYSID can no longer be specified")));
150  }
151  else if (strcmp(defel->defname, "superuser") == 0)
152  {
153  if (dissuper)
154  ereport(ERROR,
155  (errcode(ERRCODE_SYNTAX_ERROR),
156  errmsg("conflicting or redundant options"),
157  parser_errposition(pstate, defel->location)));
158  dissuper = defel;
159  }
160  else if (strcmp(defel->defname, "inherit") == 0)
161  {
162  if (dinherit)
163  ereport(ERROR,
164  (errcode(ERRCODE_SYNTAX_ERROR),
165  errmsg("conflicting or redundant options"),
166  parser_errposition(pstate, defel->location)));
167  dinherit = defel;
168  }
169  else if (strcmp(defel->defname, "createrole") == 0)
170  {
171  if (dcreaterole)
172  ereport(ERROR,
173  (errcode(ERRCODE_SYNTAX_ERROR),
174  errmsg("conflicting or redundant options"),
175  parser_errposition(pstate, defel->location)));
176  dcreaterole = defel;
177  }
178  else if (strcmp(defel->defname, "createdb") == 0)
179  {
180  if (dcreatedb)
181  ereport(ERROR,
182  (errcode(ERRCODE_SYNTAX_ERROR),
183  errmsg("conflicting or redundant options"),
184  parser_errposition(pstate, defel->location)));
185  dcreatedb = defel;
186  }
187  else if (strcmp(defel->defname, "canlogin") == 0)
188  {
189  if (dcanlogin)
190  ereport(ERROR,
191  (errcode(ERRCODE_SYNTAX_ERROR),
192  errmsg("conflicting or redundant options"),
193  parser_errposition(pstate, defel->location)));
194  dcanlogin = defel;
195  }
196  else if (strcmp(defel->defname, "isreplication") == 0)
197  {
198  if (disreplication)
199  ereport(ERROR,
200  (errcode(ERRCODE_SYNTAX_ERROR),
201  errmsg("conflicting or redundant options"),
202  parser_errposition(pstate, defel->location)));
203  disreplication = defel;
204  }
205  else if (strcmp(defel->defname, "connectionlimit") == 0)
206  {
207  if (dconnlimit)
208  ereport(ERROR,
209  (errcode(ERRCODE_SYNTAX_ERROR),
210  errmsg("conflicting or redundant options"),
211  parser_errposition(pstate, defel->location)));
212  dconnlimit = defel;
213  }
214  else if (strcmp(defel->defname, "addroleto") == 0)
215  {
216  if (daddroleto)
217  ereport(ERROR,
218  (errcode(ERRCODE_SYNTAX_ERROR),
219  errmsg("conflicting or redundant options"),
220  parser_errposition(pstate, defel->location)));
221  daddroleto = defel;
222  }
223  else if (strcmp(defel->defname, "rolemembers") == 0)
224  {
225  if (drolemembers)
226  ereport(ERROR,
227  (errcode(ERRCODE_SYNTAX_ERROR),
228  errmsg("conflicting or redundant options"),
229  parser_errposition(pstate, defel->location)));
230  drolemembers = defel;
231  }
232  else if (strcmp(defel->defname, "adminmembers") == 0)
233  {
234  if (dadminmembers)
235  ereport(ERROR,
236  (errcode(ERRCODE_SYNTAX_ERROR),
237  errmsg("conflicting or redundant options"),
238  parser_errposition(pstate, defel->location)));
239  dadminmembers = defel;
240  }
241  else if (strcmp(defel->defname, "validUntil") == 0)
242  {
243  if (dvalidUntil)
244  ereport(ERROR,
245  (errcode(ERRCODE_SYNTAX_ERROR),
246  errmsg("conflicting or redundant options"),
247  parser_errposition(pstate, defel->location)));
248  dvalidUntil = defel;
249  }
250  else if (strcmp(defel->defname, "bypassrls") == 0)
251  {
252  if (dbypassRLS)
253  ereport(ERROR,
254  (errcode(ERRCODE_SYNTAX_ERROR),
255  errmsg("conflicting or redundant options"),
256  parser_errposition(pstate, defel->location)));
257  dbypassRLS = defel;
258  }
259  else
260  elog(ERROR, "option \"%s\" not recognized",
261  defel->defname);
262  }
263 
264  if (dpassword && dpassword->arg)
265  password = strVal(dpassword->arg);
266  if (dissuper)
267  issuper = intVal(dissuper->arg) != 0;
268  if (dinherit)
269  inherit = intVal(dinherit->arg) != 0;
270  if (dcreaterole)
271  createrole = intVal(dcreaterole->arg) != 0;
272  if (dcreatedb)
273  createdb = intVal(dcreatedb->arg) != 0;
274  if (dcanlogin)
275  canlogin = intVal(dcanlogin->arg) != 0;
276  if (disreplication)
277  isreplication = intVal(disreplication->arg) != 0;
278  if (dconnlimit)
279  {
280  connlimit = intVal(dconnlimit->arg);
281  if (connlimit < -1)
282  ereport(ERROR,
283  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
284  errmsg("invalid connection limit: %d", connlimit)));
285  }
286  if (daddroleto)
287  addroleto = (List *) daddroleto->arg;
288  if (drolemembers)
289  rolemembers = (List *) drolemembers->arg;
290  if (dadminmembers)
291  adminmembers = (List *) dadminmembers->arg;
292  if (dvalidUntil)
293  validUntil = strVal(dvalidUntil->arg);
294  if (dbypassRLS)
295  bypassrls = intVal(dbypassRLS->arg) != 0;
296 
297  /* Check some permissions first */
298  if (issuper)
299  {
300  if (!superuser())
301  ereport(ERROR,
302  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
303  errmsg("must be superuser to create superusers")));
304  }
305  else if (isreplication)
306  {
307  if (!superuser())
308  ereport(ERROR,
309  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
310  errmsg("must be superuser to create replication users")));
311  }
312  else if (bypassrls)
313  {
314  if (!superuser())
315  ereport(ERROR,
316  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
317  errmsg("must be superuser to change bypassrls attribute")));
318  }
319  else
320  {
322  ereport(ERROR,
323  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
324  errmsg("permission denied to create role")));
325  }
326 
327  /*
328  * Check that the user is not trying to create a role in the reserved
329  * "pg_" namespace.
330  */
331  if (IsReservedName(stmt->role))
332  ereport(ERROR,
333  (errcode(ERRCODE_RESERVED_NAME),
334  errmsg("role name \"%s\" is reserved",
335  stmt->role),
336  errdetail("Role names starting with \"pg_\" are reserved.")));
337 
338  /*
339  * Check the pg_authid relation to be certain the role doesn't already
340  * exist.
341  */
342  pg_authid_rel = heap_open(AuthIdRelationId, RowExclusiveLock);
343  pg_authid_dsc = RelationGetDescr(pg_authid_rel);
344 
345  if (OidIsValid(get_role_oid(stmt->role, true)))
346  ereport(ERROR,
348  errmsg("role \"%s\" already exists",
349  stmt->role)));
350 
351  /* Convert validuntil to internal form */
352  if (validUntil)
353  {
354  validUntil_datum = DirectFunctionCall3(timestamptz_in,
355  CStringGetDatum(validUntil),
357  Int32GetDatum(-1));
358  validUntil_null = false;
359  }
360  else
361  {
362  validUntil_datum = (Datum) 0;
363  validUntil_null = true;
364  }
365 
366  /*
367  * Call the password checking hook if there is one defined
368  */
369  if (check_password_hook && password)
370  (*check_password_hook) (stmt->role,
371  password,
372  get_password_type(password),
373  validUntil_datum,
374  validUntil_null);
375 
376  /*
377  * Build a tuple to insert
378  */
379  MemSet(new_record, 0, sizeof(new_record));
380  MemSet(new_record_nulls, false, sizeof(new_record_nulls));
381 
382  new_record[Anum_pg_authid_rolname - 1] =
384 
385  new_record[Anum_pg_authid_rolsuper - 1] = BoolGetDatum(issuper);
386  new_record[Anum_pg_authid_rolinherit - 1] = BoolGetDatum(inherit);
387  new_record[Anum_pg_authid_rolcreaterole - 1] = BoolGetDatum(createrole);
388  new_record[Anum_pg_authid_rolcreatedb - 1] = BoolGetDatum(createdb);
389  new_record[Anum_pg_authid_rolcanlogin - 1] = BoolGetDatum(canlogin);
390  new_record[Anum_pg_authid_rolreplication - 1] = BoolGetDatum(isreplication);
391  new_record[Anum_pg_authid_rolconnlimit - 1] = Int32GetDatum(connlimit);
392 
393  if (password)
394  {
395  /* Encrypt the password to the requested format. */
396  char *shadow_pass;
397 
398  shadow_pass = encrypt_password(password_type, stmt->role, password);
399  new_record[Anum_pg_authid_rolpassword - 1] =
400  CStringGetTextDatum(shadow_pass);
401  }
402  else
403  new_record_nulls[Anum_pg_authid_rolpassword - 1] = true;
404 
405  new_record[Anum_pg_authid_rolvaliduntil - 1] = validUntil_datum;
406  new_record_nulls[Anum_pg_authid_rolvaliduntil - 1] = validUntil_null;
407 
408  new_record[Anum_pg_authid_rolbypassrls - 1] = BoolGetDatum(bypassrls);
409 
410  tuple = heap_form_tuple(pg_authid_dsc, new_record, new_record_nulls);
411 
412  /*
413  * pg_largeobject_metadata contains pg_authid.oid's, so we use the
414  * binary-upgrade override.
415  */
416  if (IsBinaryUpgrade)
417  {
419  ereport(ERROR,
420  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
421  errmsg("pg_authid OID value not set when in binary upgrade mode")));
422 
425  }
426 
427  /*
428  * Insert new record in the pg_authid table
429  */
430  roleid = CatalogTupleInsert(pg_authid_rel, tuple);
431 
432  /*
433  * Advance command counter so we can see new record; else tests in
434  * AddRoleMems may fail.
435  */
436  if (addroleto || adminmembers || rolemembers)
438 
439  /*
440  * Add the new role to the specified existing roles.
441  */
442  foreach(item, addroleto)
443  {
444  RoleSpec *oldrole = lfirst(item);
445  HeapTuple oldroletup = get_rolespec_tuple(oldrole);
446  Oid oldroleid = HeapTupleGetOid(oldroletup);
447  char *oldrolename = NameStr(((Form_pg_authid) GETSTRUCT(oldroletup))->rolname);
448 
449  AddRoleMems(oldrolename, oldroleid,
450  list_make1(makeString(stmt->role)),
451  list_make1_oid(roleid),
452  GetUserId(), false);
453 
454  ReleaseSysCache(oldroletup);
455  }
456 
457  /*
458  * Add the specified members to this new role. adminmembers get the admin
459  * option, rolemembers don't.
460  */
461  AddRoleMems(stmt->role, roleid,
462  adminmembers, roleSpecsToIds(adminmembers),
463  GetUserId(), true);
464  AddRoleMems(stmt->role, roleid,
465  rolemembers, roleSpecsToIds(rolemembers),
466  GetUserId(), false);
467 
468  /* Post creation hook for new role */
470 
471  /*
472  * Close pg_authid, but keep lock till commit.
473  */
474  heap_close(pg_authid_rel, NoLock);
475 
476  return roleid;
477 }
478 
479 
480 /*
481  * ALTER ROLE
482  *
483  * Note: the rolemembers option accepted here is intended to support the
484  * backwards-compatible ALTER GROUP syntax. Although it will work to say
485  * "ALTER ROLE role ROLE rolenames", we don't document it.
486  */
487 Oid
489 {
490  Datum new_record[Natts_pg_authid];
491  bool new_record_nulls[Natts_pg_authid];
492  bool new_record_repl[Natts_pg_authid];
493  Relation pg_authid_rel;
494  TupleDesc pg_authid_dsc;
495  HeapTuple tuple,
496  new_tuple;
497  Form_pg_authid authform;
498  ListCell *option;
499  char *rolename = NULL;
500  char *password = NULL; /* user password */
501  int password_type = Password_encryption;
502  int issuper = -1; /* Make the user a superuser? */
503  int inherit = -1; /* Auto inherit privileges? */
504  int createrole = -1; /* Can this user create roles? */
505  int createdb = -1; /* Can the user create databases? */
506  int canlogin = -1; /* Can this user login? */
507  int isreplication = -1; /* Is this a replication role? */
508  int connlimit = -1; /* maximum connections allowed */
509  List *rolemembers = NIL; /* roles to be added/removed */
510  char *validUntil = NULL; /* time the login is valid until */
511  Datum validUntil_datum; /* same, as timestamptz Datum */
512  bool validUntil_null;
513  int bypassrls = -1;
514  DefElem *dpassword = NULL;
515  DefElem *dissuper = NULL;
516  DefElem *dinherit = NULL;
517  DefElem *dcreaterole = NULL;
518  DefElem *dcreatedb = NULL;
519  DefElem *dcanlogin = NULL;
520  DefElem *disreplication = NULL;
521  DefElem *dconnlimit = NULL;
522  DefElem *drolemembers = NULL;
523  DefElem *dvalidUntil = NULL;
524  DefElem *dbypassRLS = NULL;
525  Oid roleid;
526 
528  "Cannot alter reserved roles.");
529 
530  /* Extract options from the statement node tree */
531  foreach(option, stmt->options)
532  {
533  DefElem *defel = (DefElem *) lfirst(option);
534 
535  if (strcmp(defel->defname, "password") == 0 ||
536  strcmp(defel->defname, "encryptedPassword") == 0 ||
537  strcmp(defel->defname, "unencryptedPassword") == 0)
538  {
539  if (dpassword)
540  ereport(ERROR,
541  (errcode(ERRCODE_SYNTAX_ERROR),
542  errmsg("conflicting or redundant options")));
543  dpassword = defel;
544  if (strcmp(defel->defname, "encryptedPassword") == 0)
545  password_type = PASSWORD_TYPE_MD5;
546  else if (strcmp(defel->defname, "unencryptedPassword") == 0)
547  password_type = PASSWORD_TYPE_PLAINTEXT;
548  }
549  else if (strcmp(defel->defname, "superuser") == 0)
550  {
551  if (dissuper)
552  ereport(ERROR,
553  (errcode(ERRCODE_SYNTAX_ERROR),
554  errmsg("conflicting or redundant options")));
555  dissuper = defel;
556  }
557  else if (strcmp(defel->defname, "inherit") == 0)
558  {
559  if (dinherit)
560  ereport(ERROR,
561  (errcode(ERRCODE_SYNTAX_ERROR),
562  errmsg("conflicting or redundant options")));
563  dinherit = defel;
564  }
565  else if (strcmp(defel->defname, "createrole") == 0)
566  {
567  if (dcreaterole)
568  ereport(ERROR,
569  (errcode(ERRCODE_SYNTAX_ERROR),
570  errmsg("conflicting or redundant options")));
571  dcreaterole = defel;
572  }
573  else if (strcmp(defel->defname, "createdb") == 0)
574  {
575  if (dcreatedb)
576  ereport(ERROR,
577  (errcode(ERRCODE_SYNTAX_ERROR),
578  errmsg("conflicting or redundant options")));
579  dcreatedb = defel;
580  }
581  else if (strcmp(defel->defname, "canlogin") == 0)
582  {
583  if (dcanlogin)
584  ereport(ERROR,
585  (errcode(ERRCODE_SYNTAX_ERROR),
586  errmsg("conflicting or redundant options")));
587  dcanlogin = defel;
588  }
589  else if (strcmp(defel->defname, "isreplication") == 0)
590  {
591  if (disreplication)
592  ereport(ERROR,
593  (errcode(ERRCODE_SYNTAX_ERROR),
594  errmsg("conflicting or redundant options")));
595  disreplication = defel;
596  }
597  else if (strcmp(defel->defname, "connectionlimit") == 0)
598  {
599  if (dconnlimit)
600  ereport(ERROR,
601  (errcode(ERRCODE_SYNTAX_ERROR),
602  errmsg("conflicting or redundant options")));
603  dconnlimit = defel;
604  }
605  else if (strcmp(defel->defname, "rolemembers") == 0 &&
606  stmt->action != 0)
607  {
608  if (drolemembers)
609  ereport(ERROR,
610  (errcode(ERRCODE_SYNTAX_ERROR),
611  errmsg("conflicting or redundant options")));
612  drolemembers = defel;
613  }
614  else if (strcmp(defel->defname, "validUntil") == 0)
615  {
616  if (dvalidUntil)
617  ereport(ERROR,
618  (errcode(ERRCODE_SYNTAX_ERROR),
619  errmsg("conflicting or redundant options")));
620  dvalidUntil = defel;
621  }
622  else if (strcmp(defel->defname, "bypassrls") == 0)
623  {
624  if (dbypassRLS)
625  ereport(ERROR,
626  (errcode(ERRCODE_SYNTAX_ERROR),
627  errmsg("conflicting or redundant options")));
628  dbypassRLS = defel;
629  }
630  else
631  elog(ERROR, "option \"%s\" not recognized",
632  defel->defname);
633  }
634 
635  if (dpassword && dpassword->arg)
636  password = strVal(dpassword->arg);
637  if (dissuper)
638  issuper = intVal(dissuper->arg);
639  if (dinherit)
640  inherit = intVal(dinherit->arg);
641  if (dcreaterole)
642  createrole = intVal(dcreaterole->arg);
643  if (dcreatedb)
644  createdb = intVal(dcreatedb->arg);
645  if (dcanlogin)
646  canlogin = intVal(dcanlogin->arg);
647  if (disreplication)
648  isreplication = intVal(disreplication->arg);
649  if (dconnlimit)
650  {
651  connlimit = intVal(dconnlimit->arg);
652  if (connlimit < -1)
653  ereport(ERROR,
654  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
655  errmsg("invalid connection limit: %d", connlimit)));
656  }
657  if (drolemembers)
658  rolemembers = (List *) drolemembers->arg;
659  if (dvalidUntil)
660  validUntil = strVal(dvalidUntil->arg);
661  if (dbypassRLS)
662  bypassrls = intVal(dbypassRLS->arg);
663 
664  /*
665  * Scan the pg_authid relation to be certain the user exists.
666  */
667  pg_authid_rel = heap_open(AuthIdRelationId, RowExclusiveLock);
668  pg_authid_dsc = RelationGetDescr(pg_authid_rel);
669 
670  tuple = get_rolespec_tuple(stmt->role);
671  authform = (Form_pg_authid) GETSTRUCT(tuple);
672  rolename = pstrdup(NameStr(authform->rolname));
673  roleid = HeapTupleGetOid(tuple);
674 
675  /*
676  * To mess with a superuser you gotta be superuser; else you need
677  * createrole, or just want to change your own password
678  */
679  if (authform->rolsuper || issuper >= 0)
680  {
681  if (!superuser())
682  ereport(ERROR,
683  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
684  errmsg("must be superuser to alter superusers")));
685  }
686  else if (authform->rolreplication || isreplication >= 0)
687  {
688  if (!superuser())
689  ereport(ERROR,
690  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
691  errmsg("must be superuser to alter replication users")));
692  }
693  else if (authform->rolbypassrls || bypassrls >= 0)
694  {
695  if (!superuser())
696  ereport(ERROR,
697  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
698  errmsg("must be superuser to change bypassrls attribute")));
699  }
700  else if (!have_createrole_privilege())
701  {
702  if (!(inherit < 0 &&
703  createrole < 0 &&
704  createdb < 0 &&
705  canlogin < 0 &&
706  isreplication < 0 &&
707  !dconnlimit &&
708  !rolemembers &&
709  !validUntil &&
710  dpassword &&
711  roleid == GetUserId()))
712  ereport(ERROR,
713  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
714  errmsg("permission denied")));
715  }
716 
717  /* Convert validuntil to internal form */
718  if (validUntil)
719  {
720  validUntil_datum = DirectFunctionCall3(timestamptz_in,
721  CStringGetDatum(validUntil),
723  Int32GetDatum(-1));
724  validUntil_null = false;
725  }
726  else
727  {
728  /* fetch existing setting in case hook needs it */
729  validUntil_datum = SysCacheGetAttr(AUTHNAME, tuple,
731  &validUntil_null);
732  }
733 
734  /*
735  * Call the password checking hook if there is one defined
736  */
737  if (check_password_hook && password)
738  (*check_password_hook) (rolename,
739  password,
740  get_password_type(password),
741  validUntil_datum,
742  validUntil_null);
743 
744  /*
745  * Build an updated tuple, perusing the information just obtained
746  */
747  MemSet(new_record, 0, sizeof(new_record));
748  MemSet(new_record_nulls, false, sizeof(new_record_nulls));
749  MemSet(new_record_repl, false, sizeof(new_record_repl));
750 
751  /*
752  * issuper/createrole/etc
753  */
754  if (issuper >= 0)
755  {
756  new_record[Anum_pg_authid_rolsuper - 1] = BoolGetDatum(issuper > 0);
757  new_record_repl[Anum_pg_authid_rolsuper - 1] = true;
758  }
759 
760  if (inherit >= 0)
761  {
762  new_record[Anum_pg_authid_rolinherit - 1] = BoolGetDatum(inherit > 0);
763  new_record_repl[Anum_pg_authid_rolinherit - 1] = true;
764  }
765 
766  if (createrole >= 0)
767  {
768  new_record[Anum_pg_authid_rolcreaterole - 1] = BoolGetDatum(createrole > 0);
769  new_record_repl[Anum_pg_authid_rolcreaterole - 1] = true;
770  }
771 
772  if (createdb >= 0)
773  {
774  new_record[Anum_pg_authid_rolcreatedb - 1] = BoolGetDatum(createdb > 0);
775  new_record_repl[Anum_pg_authid_rolcreatedb - 1] = true;
776  }
777 
778  if (canlogin >= 0)
779  {
780  new_record[Anum_pg_authid_rolcanlogin - 1] = BoolGetDatum(canlogin > 0);
781  new_record_repl[Anum_pg_authid_rolcanlogin - 1] = true;
782  }
783 
784  if (isreplication >= 0)
785  {
786  new_record[Anum_pg_authid_rolreplication - 1] = BoolGetDatum(isreplication > 0);
787  new_record_repl[Anum_pg_authid_rolreplication - 1] = true;
788  }
789 
790  if (dconnlimit)
791  {
792  new_record[Anum_pg_authid_rolconnlimit - 1] = Int32GetDatum(connlimit);
793  new_record_repl[Anum_pg_authid_rolconnlimit - 1] = true;
794  }
795 
796  /* password */
797  if (password)
798  {
799  /* Encrypt the password to the requested format. */
800  char *shadow_pass;
801 
802  shadow_pass = encrypt_password(password_type, rolename, password);
803  new_record[Anum_pg_authid_rolpassword - 1] =
804  CStringGetTextDatum(shadow_pass);
805  new_record_repl[Anum_pg_authid_rolpassword - 1] = true;
806  }
807 
808  /* unset password */
809  if (dpassword && dpassword->arg == NULL)
810  {
811  new_record_repl[Anum_pg_authid_rolpassword - 1] = true;
812  new_record_nulls[Anum_pg_authid_rolpassword - 1] = true;
813  }
814 
815  /* valid until */
816  new_record[Anum_pg_authid_rolvaliduntil - 1] = validUntil_datum;
817  new_record_nulls[Anum_pg_authid_rolvaliduntil - 1] = validUntil_null;
818  new_record_repl[Anum_pg_authid_rolvaliduntil - 1] = true;
819 
820  if (bypassrls >= 0)
821  {
822  new_record[Anum_pg_authid_rolbypassrls - 1] = BoolGetDatum(bypassrls > 0);
823  new_record_repl[Anum_pg_authid_rolbypassrls - 1] = true;
824  }
825 
826  new_tuple = heap_modify_tuple(tuple, pg_authid_dsc, new_record,
827  new_record_nulls, new_record_repl);
828  CatalogTupleUpdate(pg_authid_rel, &tuple->t_self, new_tuple);
829 
831 
832  ReleaseSysCache(tuple);
833  heap_freetuple(new_tuple);
834 
835  /*
836  * Advance command counter so we can see new record; else tests in
837  * AddRoleMems may fail.
838  */
839  if (rolemembers)
841 
842  if (stmt->action == +1) /* add members to role */
843  AddRoleMems(rolename, roleid,
844  rolemembers, roleSpecsToIds(rolemembers),
845  GetUserId(), false);
846  else if (stmt->action == -1) /* drop members from role */
847  DelRoleMems(rolename, roleid,
848  rolemembers, roleSpecsToIds(rolemembers),
849  false);
850 
851  /*
852  * Close pg_authid, but keep lock till commit.
853  */
854  heap_close(pg_authid_rel, NoLock);
855 
856  return roleid;
857 }
858 
859 
860 /*
861  * ALTER ROLE ... SET
862  */
863 Oid
865 {
866  HeapTuple roletuple;
867  Oid databaseid = InvalidOid;
868  Oid roleid = InvalidOid;
869 
870  if (stmt->role)
871  {
873  "Cannot alter reserved roles.");
874 
875  roletuple = get_rolespec_tuple(stmt->role);
876  roleid = HeapTupleGetOid(roletuple);
877 
878  /*
879  * Obtain a lock on the role and make sure it didn't go away in the
880  * meantime.
881  */
883 
884  /*
885  * To mess with a superuser you gotta be superuser; else you need
886  * createrole, or just want to change your own settings
887  */
888  if (((Form_pg_authid) GETSTRUCT(roletuple))->rolsuper)
889  {
890  if (!superuser())
891  ereport(ERROR,
892  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
893  errmsg("must be superuser to alter superusers")));
894  }
895  else
896  {
897  if (!have_createrole_privilege() &&
898  HeapTupleGetOid(roletuple) != GetUserId())
899  ereport(ERROR,
900  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
901  errmsg("permission denied")));
902  }
903 
904  ReleaseSysCache(roletuple);
905  }
906 
907  /* look up and lock the database, if specified */
908  if (stmt->database != NULL)
909  {
910  databaseid = get_database_oid(stmt->database, false);
912 
913  if (!stmt->role)
914  {
915  /*
916  * If no role is specified, then this is effectively the same as
917  * ALTER DATABASE ... SET, so use the same permission check.
918  */
919  if (!pg_database_ownercheck(databaseid, GetUserId()))
921  stmt->database);
922  }
923  }
924 
925  if (!stmt->role && !stmt->database)
926  {
927  /* Must be superuser to alter settings globally. */
928  if (!superuser())
929  ereport(ERROR,
930  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
931  errmsg("must be superuser to alter settings globally")));
932  }
933 
934  AlterSetting(databaseid, roleid, stmt->setstmt);
935 
936  return roleid;
937 }
938 
939 
940 /*
941  * DROP ROLE
942  */
943 void
945 {
946  Relation pg_authid_rel,
947  pg_auth_members_rel;
948  ListCell *item;
949 
951  ereport(ERROR,
952  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
953  errmsg("permission denied to drop role")));
954 
955  /*
956  * Scan the pg_authid relation to find the Oid of the role(s) to be
957  * deleted.
958  */
959  pg_authid_rel = heap_open(AuthIdRelationId, RowExclusiveLock);
960  pg_auth_members_rel = heap_open(AuthMemRelationId, RowExclusiveLock);
961 
962  foreach(item, stmt->roles)
963  {
964  RoleSpec *rolspec = lfirst(item);
965  char *role;
966  HeapTuple tuple,
967  tmp_tuple;
968  ScanKeyData scankey;
969  char *detail;
970  char *detail_log;
971  SysScanDesc sscan;
972  Oid roleid;
973 
974  if (rolspec->roletype != ROLESPEC_CSTRING)
975  ereport(ERROR,
976  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
977  errmsg("cannot use special role specifier in DROP ROLE")));
978  role = rolspec->rolename;
979 
980  tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
981  if (!HeapTupleIsValid(tuple))
982  {
983  if (!stmt->missing_ok)
984  {
985  ereport(ERROR,
986  (errcode(ERRCODE_UNDEFINED_OBJECT),
987  errmsg("role \"%s\" does not exist", role)));
988  }
989  else
990  {
991  ereport(NOTICE,
992  (errmsg("role \"%s\" does not exist, skipping",
993  role)));
994  }
995 
996  continue;
997  }
998 
999  roleid = HeapTupleGetOid(tuple);
1000 
1001  if (roleid == GetUserId())
1002  ereport(ERROR,
1003  (errcode(ERRCODE_OBJECT_IN_USE),
1004  errmsg("current user cannot be dropped")));
1005  if (roleid == GetOuterUserId())
1006  ereport(ERROR,
1007  (errcode(ERRCODE_OBJECT_IN_USE),
1008  errmsg("current user cannot be dropped")));
1009  if (roleid == GetSessionUserId())
1010  ereport(ERROR,
1011  (errcode(ERRCODE_OBJECT_IN_USE),
1012  errmsg("session user cannot be dropped")));
1013 
1014  /*
1015  * For safety's sake, we allow createrole holders to drop ordinary
1016  * roles but not superuser roles. This is mainly to avoid the
1017  * scenario where you accidentally drop the last superuser.
1018  */
1019  if (((Form_pg_authid) GETSTRUCT(tuple))->rolsuper &&
1020  !superuser())
1021  ereport(ERROR,
1022  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1023  errmsg("must be superuser to drop superusers")));
1024 
1025  /* DROP hook for the role being removed */
1027 
1028  /*
1029  * Lock the role, so nobody can add dependencies to her while we drop
1030  * her. We keep the lock until the end of transaction.
1031  */
1033 
1034  /* Check for pg_shdepend entries depending on this role */
1036  &detail, &detail_log))
1037  ereport(ERROR,
1038  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
1039  errmsg("role \"%s\" cannot be dropped because some objects depend on it",
1040  role),
1041  errdetail_internal("%s", detail),
1042  errdetail_log("%s", detail_log)));
1043 
1044  /*
1045  * Remove the role from the pg_authid table
1046  */
1047  CatalogTupleDelete(pg_authid_rel, &tuple->t_self);
1048 
1049  ReleaseSysCache(tuple);
1050 
1051  /*
1052  * Remove role from the pg_auth_members table. We have to remove all
1053  * tuples that show it as either a role or a member.
1054  *
1055  * XXX what about grantor entries? Maybe we should do one heap scan.
1056  */
1057  ScanKeyInit(&scankey,
1059  BTEqualStrategyNumber, F_OIDEQ,
1060  ObjectIdGetDatum(roleid));
1061 
1062  sscan = systable_beginscan(pg_auth_members_rel, AuthMemRoleMemIndexId,
1063  true, NULL, 1, &scankey);
1064 
1065  while (HeapTupleIsValid(tmp_tuple = systable_getnext(sscan)))
1066  {
1067  CatalogTupleDelete(pg_auth_members_rel, &tmp_tuple->t_self);
1068  }
1069 
1070  systable_endscan(sscan);
1071 
1072  ScanKeyInit(&scankey,
1074  BTEqualStrategyNumber, F_OIDEQ,
1075  ObjectIdGetDatum(roleid));
1076 
1077  sscan = systable_beginscan(pg_auth_members_rel, AuthMemMemRoleIndexId,
1078  true, NULL, 1, &scankey);
1079 
1080  while (HeapTupleIsValid(tmp_tuple = systable_getnext(sscan)))
1081  {
1082  CatalogTupleDelete(pg_auth_members_rel, &tmp_tuple->t_self);
1083  }
1084 
1085  systable_endscan(sscan);
1086 
1087  /*
1088  * Remove any comments or security labels on this role.
1089  */
1092 
1093  /*
1094  * Remove settings for this role.
1095  */
1096  DropSetting(InvalidOid, roleid);
1097 
1098  /*
1099  * Advance command counter so that later iterations of this loop will
1100  * see the changes already made. This is essential if, for example,
1101  * we are trying to drop both a role and one of its direct members ---
1102  * we'll get an error if we try to delete the linking pg_auth_members
1103  * tuple twice. (We do not need a CCI between the two delete loops
1104  * above, because it's not allowed for a role to directly contain
1105  * itself.)
1106  */
1108  }
1109 
1110  /*
1111  * Now we can clean up; but keep locks until commit.
1112  */
1113  heap_close(pg_auth_members_rel, NoLock);
1114  heap_close(pg_authid_rel, NoLock);
1115 }
1116 
1117 /*
1118  * Rename role
1119  */
1121 RenameRole(const char *oldname, const char *newname)
1122 {
1123  HeapTuple oldtuple,
1124  newtuple;
1125  TupleDesc dsc;
1126  Relation rel;
1127  Datum datum;
1128  bool isnull;
1129  Datum repl_val[Natts_pg_authid];
1130  bool repl_null[Natts_pg_authid];
1131  bool repl_repl[Natts_pg_authid];
1132  int i;
1133  Oid roleid;
1134  ObjectAddress address;
1135  Form_pg_authid authform;
1136 
1138  dsc = RelationGetDescr(rel);
1139 
1140  oldtuple = SearchSysCache1(AUTHNAME, CStringGetDatum(oldname));
1141  if (!HeapTupleIsValid(oldtuple))
1142  ereport(ERROR,
1143  (errcode(ERRCODE_UNDEFINED_OBJECT),
1144  errmsg("role \"%s\" does not exist", oldname)));
1145 
1146  /*
1147  * XXX Client applications probably store the session user somewhere, so
1148  * renaming it could cause confusion. On the other hand, there may not be
1149  * an actual problem besides a little confusion, so think about this and
1150  * decide. Same for SET ROLE ... we don't restrict renaming the current
1151  * effective userid, though.
1152  */
1153 
1154  roleid = HeapTupleGetOid(oldtuple);
1155  authform = (Form_pg_authid) GETSTRUCT(oldtuple);
1156 
1157  if (roleid == GetSessionUserId())
1158  ereport(ERROR,
1159  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1160  errmsg("session user cannot be renamed")));
1161  if (roleid == GetOuterUserId())
1162  ereport(ERROR,
1163  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1164  errmsg("current user cannot be renamed")));
1165 
1166  /*
1167  * Check that the user is not trying to rename a system role and not
1168  * trying to rename a role into the reserved "pg_" namespace.
1169  */
1170  if (IsReservedName(NameStr(authform->rolname)))
1171  ereport(ERROR,
1172  (errcode(ERRCODE_RESERVED_NAME),
1173  errmsg("role name \"%s\" is reserved",
1174  NameStr(authform->rolname)),
1175  errdetail("Role names starting with \"pg_\" are reserved.")));
1176 
1177  if (IsReservedName(newname))
1178  ereport(ERROR,
1179  (errcode(ERRCODE_RESERVED_NAME),
1180  errmsg("role name \"%s\" is reserved",
1181  newname),
1182  errdetail("Role names starting with \"pg_\" are reserved.")));
1183 
1184  /* make sure the new name doesn't exist */
1186  ereport(ERROR,
1188  errmsg("role \"%s\" already exists", newname)));
1189 
1190  /*
1191  * createrole is enough privilege unless you want to mess with a superuser
1192  */
1193  if (((Form_pg_authid) GETSTRUCT(oldtuple))->rolsuper)
1194  {
1195  if (!superuser())
1196  ereport(ERROR,
1197  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1198  errmsg("must be superuser to rename superusers")));
1199  }
1200  else
1201  {
1203  ereport(ERROR,
1204  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1205  errmsg("permission denied to rename role")));
1206  }
1207 
1208  /* OK, construct the modified tuple */
1209  for (i = 0; i < Natts_pg_authid; i++)
1210  repl_repl[i] = false;
1211 
1212  repl_repl[Anum_pg_authid_rolname - 1] = true;
1214  CStringGetDatum(newname));
1215  repl_null[Anum_pg_authid_rolname - 1] = false;
1216 
1217  datum = heap_getattr(oldtuple, Anum_pg_authid_rolpassword, dsc, &isnull);
1218 
1219  if (!isnull && get_password_type(TextDatumGetCString(datum)) == PASSWORD_TYPE_MD5)
1220  {
1221  /* MD5 uses the username as salt, so just clear it on a rename */
1222  repl_repl[Anum_pg_authid_rolpassword - 1] = true;
1223  repl_null[Anum_pg_authid_rolpassword - 1] = true;
1224 
1225  ereport(NOTICE,
1226  (errmsg("MD5 password cleared because of role rename")));
1227  }
1228 
1229  newtuple = heap_modify_tuple(oldtuple, dsc, repl_val, repl_null, repl_repl);
1230  CatalogTupleUpdate(rel, &oldtuple->t_self, newtuple);
1231 
1233 
1234  ObjectAddressSet(address, AuthIdRelationId, roleid);
1235 
1236  ReleaseSysCache(oldtuple);
1237 
1238  /*
1239  * Close pg_authid, but keep lock till commit.
1240  */
1241  heap_close(rel, NoLock);
1242 
1243  return address;
1244 }
1245 
1246 /*
1247  * GrantRoleStmt
1248  *
1249  * Grant/Revoke roles to/from roles
1250  */
1251 void
1253 {
1254  Relation pg_authid_rel;
1255  Oid grantor;
1256  List *grantee_ids;
1257  ListCell *item;
1258 
1259  if (stmt->grantor)
1260  grantor = get_rolespec_oid(stmt->grantor, false);
1261  else
1262  grantor = GetUserId();
1263 
1264  grantee_ids = roleSpecsToIds(stmt->grantee_roles);
1265 
1266  /* AccessShareLock is enough since we aren't modifying pg_authid */
1267  pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
1268 
1269  /*
1270  * Step through all of the granted roles and add/remove entries for the
1271  * grantees, or, if admin_opt is set, then just add/remove the admin
1272  * option.
1273  *
1274  * Note: Permissions checking is done by AddRoleMems/DelRoleMems
1275  */
1276  foreach(item, stmt->granted_roles)
1277  {
1278  AccessPriv *priv = (AccessPriv *) lfirst(item);
1279  char *rolename = priv->priv_name;
1280  Oid roleid;
1281 
1282  /* Must reject priv(columns) and ALL PRIVILEGES(columns) */
1283  if (rolename == NULL || priv->cols != NIL)
1284  ereport(ERROR,
1285  (errcode(ERRCODE_INVALID_GRANT_OPERATION),
1286  errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
1287 
1288  roleid = get_role_oid(rolename, false);
1289  if (stmt->is_grant)
1290  AddRoleMems(rolename, roleid,
1291  stmt->grantee_roles, grantee_ids,
1292  grantor, stmt->admin_opt);
1293  else
1294  DelRoleMems(rolename, roleid,
1295  stmt->grantee_roles, grantee_ids,
1296  stmt->admin_opt);
1297  }
1298 
1299  /*
1300  * Close pg_authid, but keep lock till commit.
1301  */
1302  heap_close(pg_authid_rel, NoLock);
1303 }
1304 
1305 /*
1306  * DropOwnedObjects
1307  *
1308  * Drop the objects owned by a given list of roles.
1309  */
1310 void
1312 {
1313  List *role_ids = roleSpecsToIds(stmt->roles);
1314  ListCell *cell;
1315 
1316  /* Check privileges */
1317  foreach(cell, role_ids)
1318  {
1319  Oid roleid = lfirst_oid(cell);
1320 
1321  if (!has_privs_of_role(GetUserId(), roleid))
1322  ereport(ERROR,
1323  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1324  errmsg("permission denied to drop objects")));
1325  }
1326 
1327  /* Ok, do it */
1328  shdepDropOwned(role_ids, stmt->behavior);
1329 }
1330 
1331 /*
1332  * ReassignOwnedObjects
1333  *
1334  * Give the objects owned by a given list of roles away to another user.
1335  */
1336 void
1338 {
1339  List *role_ids = roleSpecsToIds(stmt->roles);
1340  ListCell *cell;
1341  Oid newrole;
1342 
1343  /* Check privileges */
1344  foreach(cell, role_ids)
1345  {
1346  Oid roleid = lfirst_oid(cell);
1347 
1348  if (!has_privs_of_role(GetUserId(), roleid))
1349  ereport(ERROR,
1350  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1351  errmsg("permission denied to reassign objects")));
1352  }
1353 
1354  /* Must have privileges on the receiving side too */
1355  newrole = get_rolespec_oid(stmt->newrole, false);
1356 
1357  if (!has_privs_of_role(GetUserId(), newrole))
1358  ereport(ERROR,
1359  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1360  errmsg("permission denied to reassign objects")));
1361 
1362  /* Ok, do it */
1363  shdepReassignOwned(role_ids, newrole);
1364 }
1365 
1366 /*
1367  * roleSpecsToIds
1368  *
1369  * Given a list of RoleSpecs, generate a list of role OIDs in the same order.
1370  *
1371  * ROLESPEC_PUBLIC is not allowed.
1372  */
1373 List *
1374 roleSpecsToIds(List *memberNames)
1375 {
1376  List *result = NIL;
1377  ListCell *l;
1378 
1379  foreach(l, memberNames)
1380  {
1381  RoleSpec *rolespec = castNode(RoleSpec, lfirst(l));
1382  Oid roleid;
1383 
1384  roleid = get_rolespec_oid(rolespec, false);
1385  result = lappend_oid(result, roleid);
1386  }
1387  return result;
1388 }
1389 
1390 /*
1391  * AddRoleMems -- Add given members to the specified role
1392  *
1393  * rolename: name of role to add to (used only for error messages)
1394  * roleid: OID of role to add to
1395  * memberSpecs: list of RoleSpec of roles to add (used only for error messages)
1396  * memberIds: OIDs of roles to add
1397  * grantorId: who is granting the membership
1398  * admin_opt: granting admin option?
1399  *
1400  * Note: caller is responsible for calling auth_file_update_needed().
1401  */
1402 static void
1403 AddRoleMems(const char *rolename, Oid roleid,
1404  List *memberSpecs, List *memberIds,
1405  Oid grantorId, bool admin_opt)
1406 {
1407  Relation pg_authmem_rel;
1408  TupleDesc pg_authmem_dsc;
1409  ListCell *specitem;
1410  ListCell *iditem;
1411 
1412  Assert(list_length(memberSpecs) == list_length(memberIds));
1413 
1414  /* Skip permission check if nothing to do */
1415  if (!memberIds)
1416  return;
1417 
1418  /*
1419  * Check permissions: must have createrole or admin option on the role to
1420  * be changed. To mess with a superuser role, you gotta be superuser.
1421  */
1422  if (superuser_arg(roleid))
1423  {
1424  if (!superuser())
1425  ereport(ERROR,
1426  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1427  errmsg("must be superuser to alter superusers")));
1428  }
1429  else
1430  {
1431  if (!have_createrole_privilege() &&
1432  !is_admin_of_role(grantorId, roleid))
1433  ereport(ERROR,
1434  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1435  errmsg("must have admin option on role \"%s\"",
1436  rolename)));
1437  }
1438 
1439  /*
1440  * The role membership grantor of record has little significance at
1441  * present. Nonetheless, inasmuch as users might look to it for a crude
1442  * audit trail, let only superusers impute the grant to a third party.
1443  *
1444  * Before lifting this restriction, give the member == role case of
1445  * is_admin_of_role() a fresh look. Ensure that the current role cannot
1446  * use an explicit grantor specification to take advantage of the session
1447  * user's self-admin right.
1448  */
1449  if (grantorId != GetUserId() && !superuser())
1450  ereport(ERROR,
1451  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1452  errmsg("must be superuser to set grantor")));
1453 
1454  pg_authmem_rel = heap_open(AuthMemRelationId, RowExclusiveLock);
1455  pg_authmem_dsc = RelationGetDescr(pg_authmem_rel);
1456 
1457  forboth(specitem, memberSpecs, iditem, memberIds)
1458  {
1459  RoleSpec *memberRole = lfirst(specitem);
1460  Oid memberid = lfirst_oid(iditem);
1461  HeapTuple authmem_tuple;
1462  HeapTuple tuple;
1463  Datum new_record[Natts_pg_auth_members];
1464  bool new_record_nulls[Natts_pg_auth_members];
1465  bool new_record_repl[Natts_pg_auth_members];
1466 
1467  /*
1468  * Refuse creation of membership loops, including the trivial case
1469  * where a role is made a member of itself. We do this by checking to
1470  * see if the target role is already a member of the proposed member
1471  * role. We have to ignore possible superuserness, however, else we
1472  * could never grant membership in a superuser-privileged role.
1473  */
1474  if (is_member_of_role_nosuper(roleid, memberid))
1475  ereport(ERROR,
1476  (errcode(ERRCODE_INVALID_GRANT_OPERATION),
1477  (errmsg("role \"%s\" is a member of role \"%s\"",
1478  rolename, get_rolespec_name(memberRole)))));
1479 
1480  /*
1481  * Check if entry for this role/member already exists; if so, give
1482  * warning unless we are adding admin option.
1483  */
1484  authmem_tuple = SearchSysCache2(AUTHMEMROLEMEM,
1485  ObjectIdGetDatum(roleid),
1486  ObjectIdGetDatum(memberid));
1487  if (HeapTupleIsValid(authmem_tuple) &&
1488  (!admin_opt ||
1489  ((Form_pg_auth_members) GETSTRUCT(authmem_tuple))->admin_option))
1490  {
1491  ereport(NOTICE,
1492  (errmsg("role \"%s\" is already a member of role \"%s\"",
1493  get_rolespec_name(memberRole), rolename)));
1494  ReleaseSysCache(authmem_tuple);
1495  continue;
1496  }
1497 
1498  /* Build a tuple to insert or update */
1499  MemSet(new_record, 0, sizeof(new_record));
1500  MemSet(new_record_nulls, false, sizeof(new_record_nulls));
1501  MemSet(new_record_repl, false, sizeof(new_record_repl));
1502 
1503  new_record[Anum_pg_auth_members_roleid - 1] = ObjectIdGetDatum(roleid);
1504  new_record[Anum_pg_auth_members_member - 1] = ObjectIdGetDatum(memberid);
1505  new_record[Anum_pg_auth_members_grantor - 1] = ObjectIdGetDatum(grantorId);
1506  new_record[Anum_pg_auth_members_admin_option - 1] = BoolGetDatum(admin_opt);
1507 
1508  if (HeapTupleIsValid(authmem_tuple))
1509  {
1510  new_record_repl[Anum_pg_auth_members_grantor - 1] = true;
1511  new_record_repl[Anum_pg_auth_members_admin_option - 1] = true;
1512  tuple = heap_modify_tuple(authmem_tuple, pg_authmem_dsc,
1513  new_record,
1514  new_record_nulls, new_record_repl);
1515  CatalogTupleUpdate(pg_authmem_rel, &tuple->t_self, tuple);
1516  ReleaseSysCache(authmem_tuple);
1517  }
1518  else
1519  {
1520  tuple = heap_form_tuple(pg_authmem_dsc,
1521  new_record, new_record_nulls);
1522  CatalogTupleInsert(pg_authmem_rel, tuple);
1523  }
1524 
1525  /* CCI after each change, in case there are duplicates in list */
1527  }
1528 
1529  /*
1530  * Close pg_authmem, but keep lock till commit.
1531  */
1532  heap_close(pg_authmem_rel, NoLock);
1533 }
1534 
1535 /*
1536  * DelRoleMems -- Remove given members from the specified role
1537  *
1538  * rolename: name of role to del from (used only for error messages)
1539  * roleid: OID of role to del from
1540  * memberSpecs: list of RoleSpec of roles to del (used only for error messages)
1541  * memberIds: OIDs of roles to del
1542  * admin_opt: remove admin option only?
1543  *
1544  * Note: caller is responsible for calling auth_file_update_needed().
1545  */
1546 static void
1547 DelRoleMems(const char *rolename, Oid roleid,
1548  List *memberSpecs, List *memberIds,
1549  bool admin_opt)
1550 {
1551  Relation pg_authmem_rel;
1552  TupleDesc pg_authmem_dsc;
1553  ListCell *specitem;
1554  ListCell *iditem;
1555 
1556  Assert(list_length(memberSpecs) == list_length(memberIds));
1557 
1558  /* Skip permission check if nothing to do */
1559  if (!memberIds)
1560  return;
1561 
1562  /*
1563  * Check permissions: must have createrole or admin option on the role to
1564  * be changed. To mess with a superuser role, you gotta be superuser.
1565  */
1566  if (superuser_arg(roleid))
1567  {
1568  if (!superuser())
1569  ereport(ERROR,
1570  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1571  errmsg("must be superuser to alter superusers")));
1572  }
1573  else
1574  {
1575  if (!have_createrole_privilege() &&
1576  !is_admin_of_role(GetUserId(), roleid))
1577  ereport(ERROR,
1578  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1579  errmsg("must have admin option on role \"%s\"",
1580  rolename)));
1581  }
1582 
1583  pg_authmem_rel = heap_open(AuthMemRelationId, RowExclusiveLock);
1584  pg_authmem_dsc = RelationGetDescr(pg_authmem_rel);
1585 
1586  forboth(specitem, memberSpecs, iditem, memberIds)
1587  {
1588  RoleSpec *memberRole = lfirst(specitem);
1589  Oid memberid = lfirst_oid(iditem);
1590  HeapTuple authmem_tuple;
1591 
1592  /*
1593  * Find entry for this role/member
1594  */
1595  authmem_tuple = SearchSysCache2(AUTHMEMROLEMEM,
1596  ObjectIdGetDatum(roleid),
1597  ObjectIdGetDatum(memberid));
1598  if (!HeapTupleIsValid(authmem_tuple))
1599  {
1600  ereport(WARNING,
1601  (errmsg("role \"%s\" is not a member of role \"%s\"",
1602  get_rolespec_name(memberRole), rolename)));
1603  continue;
1604  }
1605 
1606  if (!admin_opt)
1607  {
1608  /* Remove the entry altogether */
1609  CatalogTupleDelete(pg_authmem_rel, &authmem_tuple->t_self);
1610  }
1611  else
1612  {
1613  /* Just turn off the admin option */
1614  HeapTuple tuple;
1615  Datum new_record[Natts_pg_auth_members];
1616  bool new_record_nulls[Natts_pg_auth_members];
1617  bool new_record_repl[Natts_pg_auth_members];
1618 
1619  /* Build a tuple to update with */
1620  MemSet(new_record, 0, sizeof(new_record));
1621  MemSet(new_record_nulls, false, sizeof(new_record_nulls));
1622  MemSet(new_record_repl, false, sizeof(new_record_repl));
1623 
1624  new_record[Anum_pg_auth_members_admin_option - 1] = BoolGetDatum(false);
1625  new_record_repl[Anum_pg_auth_members_admin_option - 1] = true;
1626 
1627  tuple = heap_modify_tuple(authmem_tuple, pg_authmem_dsc,
1628  new_record,
1629  new_record_nulls, new_record_repl);
1630  CatalogTupleUpdate(pg_authmem_rel, &tuple->t_self, tuple);
1631  }
1632 
1633  ReleaseSysCache(authmem_tuple);
1634 
1635  /* CCI after each change, in case there are duplicates in list */
1637  }
1638 
1639  /*
1640  * Close pg_authmem, but keep lock till commit.
1641  */
1642  heap_close(pg_authmem_rel, NoLock);
1643 }
bool has_createrole_privilege(Oid roleid)
Definition: aclchk.c:5119
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:69
static char password[100]
Definition: streamutil.c:44
RoleSpec * role
Definition: parsenodes.h:2329
void shdepDropOwned(List *roleids, DropBehavior behavior)
Definition: pg_shdepend.c:1162
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:46
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:174
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:493
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Oid binary_upgrade_next_pg_authid_oid
Definition: user.c:43
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:145
#define RelationGetDescr(relation)
Definition: rel.h:425
Oid GetUserId(void)
Definition: miscinit.c:283
int Password_encryption
Definition: user.c:47
#define castNode(_type_, nodeptr)
Definition: nodes.h:577
#define PointerGetDatum(X)
Definition: postgres.h:564
#define AuthMemRelationId
RoleStmtType stmt_type
Definition: parsenodes.h:2321
char * pstrdup(const char *in)
Definition: mcxt.c:1165
#define DatabaseRelationId
Definition: pg_database.h:29
PasswordType get_password_type(const char *shadow_pass)
Definition: crypt.c:110
void DropOwnedObjects(DropOwnedStmt *stmt)
Definition: user.c:1311
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:4831
void AlterSetting(Oid databaseid, Oid roleid, VariableSetStmt *setstmt)
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:154
bool is_admin_of_role(Oid member, Oid role)
Definition: acl.c:4913
#define AccessShareLock
Definition: lockdefs.h:36
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
bool superuser(void)
Definition: superuser.c:47
#define MemSet(start, val, len)
Definition: c.h:853
#define Anum_pg_authid_rolpassword
Definition: pg_authid.h:88
List * granted_roles
Definition: parsenodes.h:1803
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:255
RoleSpec * role
Definition: parsenodes.h:2337
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:692
#define Anum_pg_authid_rolreplication
Definition: pg_authid.h:85
List * roles
Definition: parsenodes.h:2345
#define heap_close(r, l)
Definition: heapam.h:97
List * cols
Definition: parsenodes.h:1788
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:555
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
unsigned int Oid
Definition: postgres_ext.h:31
bool IsReservedName(const char *name)
Definition: catalog.c:193
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
#define OidIsValid(objectId)
Definition: c.h:534
Oid GetSessionUserId(void)
Definition: miscinit.c:317
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:322
bool IsBinaryUpgrade
Definition: globals.c:101
Oid CreateRole(ParseState *pstate, CreateRoleStmt *stmt)
Definition: user.c:72
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:149
int errdetail_internal(const char *fmt,...)
Definition: elog.c:900
Oid get_role_oid(const char *rolname, bool missing_ok)
Definition: acl.c:5114
#define AuthIdRelationId
Definition: pg_authid.h:42
#define HeapTupleSetOid(tuple, oid)
Definition: htup_details.h:698
#define Natts_pg_auth_members
#define list_make1(x1)
Definition: pg_list.h:133
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:72
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:410
#define SearchSysCacheExists1(cacheId, key1)
Definition: syscache.h:167
Oid GetOuterUserId(void)
Definition: miscinit.c:294
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:43
Oid CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:162
void GrantRole(GrantRoleStmt *stmt)
Definition: user.c:1252
#define Anum_pg_authid_rolvaliduntil
Definition: pg_authid.h:89
static void AddRoleMems(const char *rolename, Oid roleid, List *memberSpecs, List *memberIds, Oid grantorId, bool admin_opt)
Definition: user.c:1403
void shdepLockAndCheckObject(Oid classId, Oid objectId)
Definition: pg_shdepend.c:986
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
void shdepReassignOwned(List *roleids, Oid newrole)
Definition: pg_shdepend.c:1284
#define Anum_pg_authid_rolsuper
Definition: pg_authid.h:80
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3378
int location
Definition: parsenodes.h:678
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define Anum_pg_auth_members_grantor
#define CStringGetDatum(X)
Definition: postgres.h:586
#define Anum_pg_authid_rolcanlogin
Definition: pg_authid.h:84
int errdetail_log(const char *fmt,...)
Definition: elog.c:921
#define Anum_pg_authid_rolconnlimit
Definition: pg_authid.h:87
DropBehavior behavior
Definition: parsenodes.h:3203
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
RoleSpec * grantor
Definition: parsenodes.h:1807
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:4939
bool superuser_arg(Oid roleid)
Definition: superuser.c:57
#define DirectFunctionCall3(func, arg1, arg2, arg3)
Definition: fmgr.h:559
Node * arg
Definition: parsenodes.h:676
char * get_rolespec_name(const RoleSpec *role)
Definition: acl.c:5229
#define AuthMemRoleMemIndexId
Definition: indexing.h:102
#define WARNING
Definition: elog.h:40
Oid AlterRole(AlterRoleStmt *stmt)
Definition: user.c:488
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:769
#define Anum_pg_authid_rolbypassrls
Definition: pg_authid.h:86
#define TextDatumGetCString(d)
Definition: builtins.h:91
#define Anum_pg_auth_members_roleid
uintptr_t Datum
Definition: postgres.h:374
void CommandCounterIncrement(void)
Definition: xact.c:921
void check_rolespec_name(const RoleSpec *role, const char *detail_msg)
Definition: acl.c:5251
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1083
RoleSpecType roletype
Definition: parsenodes.h:319
Oid AlterRoleSet(AlterRoleSetStmt *stmt)
Definition: user.c:864
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1245
#define list_make1_oid(x1)
Definition: pg_list.h:145
Oid get_rolespec_oid(const RoleSpec *role, bool missing_ok)
Definition: acl.c:5147
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
FormData_pg_auth_members * Form_pg_auth_members
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:871
#define Anum_pg_authid_rolcreatedb
Definition: pg_authid.h:83
VariableSetStmt * setstmt
Definition: parsenodes.h:2339
char * encrypt_password(PasswordType target_type, const char *role, const char *password)
Definition: crypt.c:126
#define BoolGetDatum(X)
Definition: postgres.h:410
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:2002
#define InvalidOid
Definition: postgres_ext.h:36
ObjectAddress RenameRole(const char *oldname, const char *newname)
Definition: user.c:1121
#define NOTICE
Definition: elog.h:37
List * roleSpecsToIds(List *memberNames)
Definition: user.c:1374
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
void DeleteSharedComments(Oid oid, Oid classoid)
Definition: comment.c:373
List * options
Definition: parsenodes.h:2330
#define AuthMemMemRoleIndexId
Definition: indexing.h:104
HeapTuple get_rolespec_tuple(const RoleSpec *role)
Definition: acl.c:5185
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:109
RoleSpec * newrole
Definition: parsenodes.h:3213
char * rolename
Definition: parsenodes.h:320
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
void DeleteSharedSecurityLabel(Oid objectId, Oid classId)
Definition: seclabel.c:414
#define Anum_pg_authid_rolname
Definition: pg_authid.h:79
#define AccessExclusiveLock
Definition: lockdefs.h:46
#define Int32GetDatum(X)
Definition: postgres.h:487
bool is_member_of_role_nosuper(Oid member, Oid role)
Definition: acl.c:4893
Datum timestamptz_in(PG_FUNCTION_ARGS)
Definition: timestamp.c:382
#define intVal(v)
Definition: value.h:52
Oid createdb(ParseState *pstate, const CreatedbStmt *stmt)
Definition: dbcommands.c:100
int errmsg(const char *fmt,...)
Definition: elog.c:797
void ReassignOwnedObjects(ReassignOwnedStmt *stmt)
Definition: user.c:1337
static bool have_createrole_privilege(void)
Definition: user.c:62
int i
#define NameStr(name)
Definition: c.h:495
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define Anum_pg_auth_members_admin_option
#define CStringGetTextDatum(s)
Definition: builtins.h:90
void DropRole(DropRoleStmt *stmt)
Definition: user.c:944
char * defname
Definition: parsenodes.h:675
#define Anum_pg_authid_rolcreaterole
Definition: pg_authid.h:82
List * grantee_roles
Definition: parsenodes.h:1804
#define elog
Definition: elog.h:219
bool checkSharedDependencies(Oid classId, Oid objectId, char **detail_msg, char **detail_log_msg)
Definition: pg_shdepend.c:521
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:793
check_password_hook_type check_password_hook
Definition: user.c:50
void DropSetting(Oid databaseid, Oid roleid)
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:34
Definition: pg_list.h:45
#define Anum_pg_authid_rolinherit
Definition: pg_authid.h:81
#define BTEqualStrategyNumber
Definition: stratnum.h:31
void(* check_password_hook_type)(const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null)
Definition: user.h:23
char * priv_name
Definition: parsenodes.h:1787
#define lfirst_oid(lc)
Definition: pg_list.h:108
#define Natts_pg_authid
Definition: pg_authid.h:78
static void DelRoleMems(const char *rolename, Oid roleid, List *memberSpecs, List *memberIds, bool admin_opt)
Definition: user.c:1547
#define Anum_pg_auth_members_member
#define SearchSysCache2(cacheId, key1, key2)
Definition: syscache.h:151