diff --git a/doc/src/sgml/catalogs.sgml b/doc/src/sgml/catalogs.sgml index 086fafc..3f4724c 100644 --- a/doc/src/sgml/catalogs.sgml +++ b/doc/src/sgml/catalogs.sgml @@ -7804,6 +7804,11 @@ + pg_hba_rules + summary of client authentication configuration file contents + + + pg_group groups of database users @@ -8352,6 +8357,125 @@ + + <structname>pg_hba_rules</structname> + + + pg_hba_rules + + + + The view pg_hba_rules provides a summary of + the contents of the client authentication configuration file. A row + appears in this view for each entry appearing in the file, with annotations + indicating whether the rule could be applied successfully. + + + + <structname>pg_hba_rules</> Columns + + + + + Name + Type + Description + + + + + line_number + integer + + Line number of the client authentication rule in + pg_hba.conf file + + + + type + text + Type of connection + + + database + text[] + List of database names + + + user_name + text[] + List of user names + + + address + text + + Address specifies the set of hosts the record matches. + It can be a host name, or it is made up of an IP address + or keywords such as (all, + samehost and samenet). + + + + netmask + text + Address mask if exist + + + auth_method + text + Authentication method + + + options + text[] + Configuration options set for authentication method + + + error + text + + If not null, an error message indicates why this + rule could not be loaded. + + + + +
+ + + error field, if not NULL, describes problem + in the rule on the line line_number. + Following is the sample output of the view. + + + +SELECT line_number, type, database, user_name, auth_method FROM pg_hba_rules; + + + + line_number | type | database | user_name | address | auth_method +-------------+-------+------------+------------+--------------+------------- + 84 | local | {all} | {all} | | trust + 86 | host | {sameuser} | {postgres} | all | trust + 88 | host | {postgres} | {postgres} | ::1 | trust + 111 | host | {all} | {all} | 127.0.0.1 | trust + 121 | host | {all} | {all} | localhost | trust + 128 | host | {postgres} | {all} | samenet | ident + 134 | host | {postgres} | {all} | samehost | md5 + 140 | host | {db1,db2} | {all} | .example.com | md5 + 149 | host | {test} | {test} | 192.168.54.1 | reject + 159 | host | {all} | {+support} | 192.168.0.0 | ident + 169 | local | {sameuser} | {all} | | md5 +(11 rows) + + + + See for more information about the various + ways to change client authentication configuration. + +
+ <structname>pg_group</structname> diff --git a/doc/src/sgml/client-auth.sgml b/doc/src/sgml/client-auth.sgml index dda5891..f20486c 100644 --- a/doc/src/sgml/client-auth.sgml +++ b/doc/src/sgml/client-auth.sgml @@ -54,6 +54,13 @@ database user names and OS user names. + + The system view + pg_hba_rules + can be helpful for pre-testing changes to the client authentication configuration file, or for + diagnosing problems if loading of file did not have the desired effects. + + The <filename>pg_hba.conf</filename> File diff --git a/src/backend/catalog/system_views.sql b/src/backend/catalog/system_views.sql index 4dfedf8..d920a72 100644 --- a/src/backend/catalog/system_views.sql +++ b/src/backend/catalog/system_views.sql @@ -459,6 +459,12 @@ CREATE VIEW pg_file_settings AS REVOKE ALL on pg_file_settings FROM PUBLIC; REVOKE EXECUTE ON FUNCTION pg_show_all_file_settings() FROM PUBLIC; +CREATE VIEW pg_hba_rules AS + SELECT * FROM pg_hba_rules() AS A; + +REVOKE ALL on pg_hba_rules FROM PUBLIC; +REVOKE EXECUTE ON FUNCTION pg_hba_rules() FROM PUBLIC; + CREATE VIEW pg_timezone_abbrevs AS SELECT * FROM pg_timezone_abbrevs(); diff --git a/src/backend/libpq/hba.c b/src/backend/libpq/hba.c index bbe0a88..6986383 100644 --- a/src/backend/libpq/hba.c +++ b/src/backend/libpq/hba.c @@ -25,15 +25,22 @@ #include #include +#include "access/htup_details.h" +#include "catalog/objectaddress.h" #include "catalog/pg_collation.h" +#include "catalog/pg_type.h" #include "common/ip.h" +#include "funcapi.h" #include "libpq/ifaddr.h" #include "libpq/libpq.h" +#include "miscadmin.h" #include "postmaster/postmaster.h" #include "regex/regex.h" #include "replication/walsender.h" #include "storage/fd.h" +#include "storage/ipc.h" #include "utils/acl.h" +#include "utils/builtins.h" #include "utils/guc.h" #include "utils/lsyscache.h" #include "utils/memutils.h" @@ -86,9 +93,34 @@ typedef struct TokenizedLine List *fields; /* List of lists of HbaTokens */ int line_num; /* Line number */ char *raw_line; /* Raw line text */ + char *err_msg; /* Error message in the line if any */ } TokenizedLine; /* + * The following character array represents the names of the authentication + * methods that are supported by the PostgreSQL. + * + * NOTE: This structure should be in sync with the UserAuth enum. + */ +static char *UserAuthName[] = +{ + "reject", + "implict reject", /* Not possible to set by user */ + "trust", + "ident", + "password", + "md5", + "gss", + "sspi", + "pam", + "bsd", + "ldap", + "cert", + "radius", + "peer" +}; + +/* * pre-parsed content of HBA config file: list of HbaLine structs. * parsed_hba_context is the memory context where it lives. */ @@ -108,11 +140,15 @@ static MemoryContext parsed_ident_context = NULL; static MemoryContext tokenize_file(const char *filename, FILE *file, - List **tok_lines); + List **tok_lines, int level); static List *tokenize_inc_file(List *tokens, const char *outer_filename, - const char *inc_filename); + const char *inc_filename, int level, char **err_msg); static bool parse_hba_auth_opt(char *name, char *val, HbaLine *hbaline, - int line_num); + int line_num, int level, char **err_msg); +static Datum gethba_options(HbaLine *hba); +static void fill_hba_line(TupleDesc tupdesc, Tuplestorestate *tuple_store, + int lineno, HbaLine *hba, const char *err_msg); +static void fill_hba(TupleDesc tupdesc, Tuplestorestate *tuple_store); /* * isblank() exists in the ISO C99 spec, but it's not very portable yet, @@ -151,7 +187,7 @@ pg_isblank(const char c) */ static bool next_token(char **lineptr, char *buf, int bufsz, bool *initial_quote, - bool *terminating_comma) + bool *terminating_comma, int level, char **err_msg) { int c; char *start_buf = buf; @@ -197,10 +233,12 @@ next_token(char **lineptr, char *buf, int bufsz, bool *initial_quote, if (buf >= end_buf) { *buf = '\0'; - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("authentication file token too long, skipping: \"%s\"", start_buf))); + *err_msg = psprintf("authentication file token too long, skipping: \"%s\"", + start_buf); /* Discard remainder of line */ while ((c = (*(*lineptr)++)) != '\0' && c != '\n') ; @@ -279,7 +317,7 @@ copy_hba_token(HbaToken *in) * or NIL if we reached EOL. */ static List * -next_field_expand(const char *filename, char **lineptr) +next_field_expand(const char *filename, char **lineptr, int level, char **err_msg) { char buf[MAX_TOKEN]; bool trailing_comma; @@ -288,15 +326,15 @@ next_field_expand(const char *filename, char **lineptr) do { - if (!next_token(lineptr, buf, sizeof(buf), &initial_quote, &trailing_comma)) + if (!next_token(lineptr, buf, sizeof(buf), &initial_quote, &trailing_comma, level, err_msg) || (*err_msg != NULL)) break; /* Is this referencing a file? */ if (!initial_quote && buf[0] == '@' && buf[1] != '\0') - tokens = tokenize_inc_file(tokens, filename, buf + 1); + tokens = tokenize_inc_file(tokens, filename, buf + 1, level, err_msg); else tokens = lappend(tokens, make_hba_token(buf, initial_quote)); - } while (trailing_comma); + } while (trailing_comma && (*err_msg == NULL)); return tokens; } @@ -313,7 +351,9 @@ next_field_expand(const char *filename, char **lineptr) static List * tokenize_inc_file(List *tokens, const char *outer_filename, - const char *inc_filename) + const char *inc_filename, + int level, + char **err_msg) { char *inc_fullname; FILE *inc_file; @@ -340,16 +380,20 @@ tokenize_inc_file(List *tokens, inc_file = AllocateFile(inc_fullname, "r"); if (inc_file == NULL) { - ereport(LOG, + int save_errno = errno; + + ereport(level, (errcode_for_file_access(), errmsg("could not open secondary authentication file \"@%s\" as \"%s\": %m", inc_filename, inc_fullname))); + *err_msg = psprintf("could not open secondary authentication file \"@%s\" as \"%s\": \"%s\"", + inc_filename, inc_fullname, strerror(save_errno)); pfree(inc_fullname); return tokens; } /* There is possible recursion here if the file contains @ */ - linecxt = tokenize_file(inc_fullname, inc_file, &inc_lines); + linecxt = tokenize_file(inc_fullname, inc_file, &inc_lines, level); FreeFile(inc_file); pfree(inc_fullname); @@ -389,7 +433,7 @@ tokenize_inc_file(List *tokens, * this function (it's a child of caller's context). */ static MemoryContext -tokenize_file(const char *filename, FILE *file, List **tok_lines) +tokenize_file(const char *filename, FILE *file, List **tok_lines, int level) { int line_number = 1; MemoryContext linecxt; @@ -407,6 +451,7 @@ tokenize_file(const char *filename, FILE *file, List **tok_lines) char rawline[MAX_LINE]; char *lineptr; List *current_line = NIL; + char *err_msg = NULL; if (!fgets(rawline, sizeof(rawline), file)) break; @@ -425,11 +470,11 @@ tokenize_file(const char *filename, FILE *file, List **tok_lines) /* Parse fields */ lineptr = rawline; - while (*lineptr) + while (*lineptr && (err_msg == NULL)) { List *current_field; - current_field = next_field_expand(filename, &lineptr); + current_field = next_field_expand(filename, &lineptr, level, &err_msg); /* add field to line, unless we are at EOL or comment start */ if (current_field != NIL) current_line = lappend(current_line, current_field); @@ -444,6 +489,7 @@ tokenize_file(const char *filename, FILE *file, List **tok_lines) tok_line->fields = current_line; tok_line->line_num = line_number; tok_line->raw_line = pstrdup(rawline); + tok_line->err_msg = err_msg; *tok_lines = lappend(*tok_lines, tok_line); } @@ -755,13 +801,15 @@ check_same_host_or_net(SockAddr *raddr, IPCompareMethod method) * reporting error if it's not. */ #define INVALID_AUTH_OPTION(optname, validmethods) do {\ - ereport(LOG, \ + ereport(level, \ (errcode(ERRCODE_CONFIG_FILE_ERROR), \ /* translator: the second %s is a list of auth methods */ \ errmsg("authentication option \"%s\" is only valid for authentication methods %s", \ optname, _(validmethods)), \ errcontext("line %d of configuration file \"%s\"", \ line_num, HbaFileName))); \ + *err_msg = psprintf("authentication option \"%s\" is only valid for authentication methods %s", \ + optname, validmethods); \ return false; \ } while (0); @@ -772,12 +820,14 @@ check_same_host_or_net(SockAddr *raddr, IPCompareMethod method) #define MANDATORY_AUTH_ARG(argvar, argname, authname) do {\ if (argvar == NULL) {\ - ereport(LOG, \ + ereport(level, \ (errcode(ERRCODE_CONFIG_FILE_ERROR), \ errmsg("authentication method \"%s\" requires argument \"%s\" to be set", \ authname, argname), \ errcontext("line %d of configuration file \"%s\"", \ line_num, HbaFileName))); \ + tok_line->err_msg = psprintf("authentication method \"%s\" requires argument \"%s\" to be set", \ + authname, argname); \ return NULL; \ } \ } while (0); @@ -824,7 +874,7 @@ check_same_host_or_net(SockAddr *raddr, IPCompareMethod method) * NULL. */ static HbaLine * -parse_hba_line(TokenizedLine *tok_line) +parse_hba_line(TokenizedLine * tok_line, int level) { int line_num = tok_line->line_num; char *str; @@ -849,12 +899,13 @@ parse_hba_line(TokenizedLine *tok_line) tokens = lfirst(field); if (tokens->length > 1) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("multiple values specified for connection type"), errhint("Specify exactly one connection type per line."), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = "multiple values specified for connection type"; return NULL; } token = linitial(tokens); @@ -863,11 +914,12 @@ parse_hba_line(TokenizedLine *tok_line) #ifdef HAVE_UNIX_SOCKETS parsedline->conntype = ctLocal; #else - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("local connections are not supported by this build"), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = "local connections are not supported by this build"; return NULL; #endif } @@ -882,19 +934,23 @@ parse_hba_line(TokenizedLine *tok_line) /* Log a warning if SSL support is not active */ #ifdef USE_SSL if (!EnableSSL) - ereport(LOG, + { + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("hostssl record cannot match because SSL is disabled"), errhint("Set ssl = on in postgresql.conf."), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = "hostssl record cannot match because SSL is disabled"; + } #else - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("hostssl record cannot match because SSL is not supported by this build"), errhint("Compile with --with-openssl to use SSL connections."), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = "hostssl record cannot match because SSL is not supported by this build"; #endif } else if (token->string[4] == 'n') /* "hostnossl" */ @@ -909,12 +965,13 @@ parse_hba_line(TokenizedLine *tok_line) } /* record type */ else { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("invalid connection type \"%s\"", token->string), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = psprintf("invalid connection type \"%s\"", token->string); return NULL; } @@ -922,11 +979,12 @@ parse_hba_line(TokenizedLine *tok_line) field = lnext(field); if (!field) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("end-of-line before database specification"), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = "end-of-line before database specification"; return NULL; } parsedline->databases = NIL; @@ -941,11 +999,12 @@ parse_hba_line(TokenizedLine *tok_line) field = lnext(field); if (!field) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("end-of-line before role specification"), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = "end-of-line before role specification"; return NULL; } parsedline->roles = NIL; @@ -962,22 +1021,24 @@ parse_hba_line(TokenizedLine *tok_line) field = lnext(field); if (!field) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("end-of-line before IP address specification"), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = "end-of-line before IP address specification"; return NULL; } tokens = lfirst(field); if (tokens->length > 1) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("multiple values specified for host address"), errhint("Specify one address range per line."), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = "multiple values specified for host address"; return NULL; } token = linitial(tokens); @@ -1027,12 +1088,14 @@ parse_hba_line(TokenizedLine *tok_line) parsedline->hostname = str; else { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("invalid IP address \"%s\": %s", str, gai_strerror(ret)), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = psprintf("invalid IP address \"%s\": %s", + str, gai_strerror(ret)); if (gai_result) pg_freeaddrinfo_all(hints.ai_family, gai_result); return NULL; @@ -1045,24 +1108,28 @@ parse_hba_line(TokenizedLine *tok_line) { if (parsedline->hostname) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("specifying both host name and CIDR mask is invalid: \"%s\"", token->string), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = psprintf("specifying both host name and CIDR mask is invalid: \"%s\"", + token->string); return NULL; } if (pg_sockaddr_cidr_mask(&parsedline->mask, cidr_slash + 1, parsedline->addr.ss_family) < 0) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("invalid CIDR mask in address \"%s\"", token->string), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = psprintf("invalid CIDR mask in address \"%s\"", + token->string); return NULL; } pfree(str); @@ -1074,22 +1141,24 @@ parse_hba_line(TokenizedLine *tok_line) field = lnext(field); if (!field) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("end-of-line before netmask specification"), errhint("Specify an address range in CIDR notation, or provide a separate netmask."), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = "end-of-line before netmask specification"; return NULL; } tokens = lfirst(field); if (tokens->length > 1) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("multiple values specified for netmask"), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = "multiple values specified for netmask"; return NULL; } token = linitial(tokens); @@ -1098,12 +1167,14 @@ parse_hba_line(TokenizedLine *tok_line) &hints, &gai_result); if (ret || !gai_result) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("invalid IP mask \"%s\": %s", token->string, gai_strerror(ret)), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = psprintf("invalid IP mask \"%s\": %s", + token->string, gai_strerror(ret)); if (gai_result) pg_freeaddrinfo_all(hints.ai_family, gai_result); return NULL; @@ -1115,11 +1186,12 @@ parse_hba_line(TokenizedLine *tok_line) if (parsedline->addr.ss_family != parsedline->mask.ss_family) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("IP address and mask do not match"), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = "IP address and mask do not match"; return NULL; } } @@ -1130,22 +1202,24 @@ parse_hba_line(TokenizedLine *tok_line) field = lnext(field); if (!field) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("end-of-line before authentication method"), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = "end-of-line before authentication method"; return NULL; } tokens = lfirst(field); if (tokens->length > 1) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("multiple values specified for authentication type"), errhint("Specify exactly one authentication type per line."), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = "multiple values specified for authentication type"; return NULL; } token = linitial(tokens); @@ -1177,11 +1251,12 @@ parse_hba_line(TokenizedLine *tok_line) { if (Db_user_namespace) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("MD5 authentication is not supported when \"db_user_namespace\" is enabled"), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = "MD5 authentication is not supported when \"db_user_namespace\" is enabled"; return NULL; } parsedline->auth_method = uaMD5; @@ -1214,23 +1289,27 @@ parse_hba_line(TokenizedLine *tok_line) parsedline->auth_method = uaRADIUS; else { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("invalid authentication method \"%s\"", token->string), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = psprintf("invalid authentication method \"%s\"", + token->string); return NULL; } if (unsupauth) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("invalid authentication method \"%s\": not supported by this build", token->string), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = psprintf("invalid authentication method \"%s\": not supported by this build", + token->string); return NULL; } @@ -1246,22 +1325,24 @@ parse_hba_line(TokenizedLine *tok_line) if (parsedline->conntype == ctLocal && parsedline->auth_method == uaGSS) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("gssapi authentication is not supported on local sockets"), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = "gssapi authentication is not supported on local sockets"; return NULL; } if (parsedline->conntype != ctLocal && parsedline->auth_method == uaPeer) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("peer authentication is only supported on local sockets"), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = "peer authentication is only supported on local sockets"; return NULL; } @@ -1274,11 +1355,12 @@ parse_hba_line(TokenizedLine *tok_line) if (parsedline->conntype != ctHostSSL && parsedline->auth_method == uaCert) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("cert authentication is only supported on hostssl connections"), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = "cert authentication is only supported on hostssl connections"; return NULL; } @@ -1323,16 +1405,18 @@ parse_hba_line(TokenizedLine *tok_line) /* * Got something that's not a name=value pair. */ - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("authentication option not in name=value format: %s", token->string), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = psprintf("authentication option not in name=value format: %s", + token->string); return NULL; } *val++ = '\0'; /* str now holds "name", val holds "value" */ - if (!parse_hba_auth_opt(str, val, parsedline, line_num)) + if (!parse_hba_auth_opt(str, val, parsedline, line_num, level, &tok_line->err_msg)) /* parse_hba_auth_opt already logged the error message */ return NULL; pfree(str); @@ -1360,21 +1444,23 @@ parse_hba_line(TokenizedLine *tok_line) parsedline->ldapbindpasswd || parsedline->ldapsearchattribute) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("cannot use ldapbasedn, ldapbinddn, ldapbindpasswd, ldapsearchattribute, or ldapurl together with ldapprefix"), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = "cannot use ldapbasedn, ldapbinddn, ldapbindpasswd, ldapsearchattribute, or ldapurl together with ldapprefix"; return NULL; } } else if (!parsedline->ldapbasedn) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("authentication method \"ldap\" requires argument \"ldapbasedn\", \"ldapprefix\", or \"ldapsuffix\" to be set"), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + tok_line->err_msg = "authentication method \"ldap\" requires argument \"ldapbasedn\", \"ldapprefix\", or \"ldapsuffix\" to be set"; return NULL; } } @@ -1402,7 +1488,7 @@ parse_hba_line(TokenizedLine *tok_line) * encounter an error. */ static bool -parse_hba_auth_opt(char *name, char *val, HbaLine *hbaline, int line_num) +parse_hba_auth_opt(char *name, char *val, HbaLine *hbaline, int line_num, int level, char **err_msg) { #ifdef USE_LDAP hbaline->ldapscope = LDAP_SCOPE_SUBTREE; @@ -1422,11 +1508,12 @@ parse_hba_auth_opt(char *name, char *val, HbaLine *hbaline, int line_num) { if (hbaline->conntype != ctHostSSL) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("clientcert can only be configured for \"hostssl\" rows"), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + *err_msg = "clientcert can only be configured for \"hostssl\" rows"; return false; } if (strcmp(val, "1") == 0) @@ -1437,11 +1524,12 @@ parse_hba_auth_opt(char *name, char *val, HbaLine *hbaline, int line_num) { if (hbaline->auth_method == uaCert) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("clientcert can not be set to 0 when using \"cert\" authentication"), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + *err_msg = "clientcert can not be set to 0 when using \"cert\" authentication"; return false; } hbaline->clientcert = false; @@ -1473,18 +1561,23 @@ parse_hba_auth_opt(char *name, char *val, HbaLine *hbaline, int line_num) rc = ldap_url_parse(val, &urldata); if (rc != LDAP_SUCCESS) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("could not parse LDAP URL \"%s\": %s", val, ldap_err2string(rc)))); + *err_msg = psprintf("could not parse LDAP URL \"%s\": %s", + val, ldap_err2string(rc)); return false; } if (strcmp(urldata->lud_scheme, "ldap") != 0) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("unsupported LDAP URL scheme: %s", urldata->lud_scheme))); + *err_msg = psprintf("unsupported LDAP URL scheme: %s", + urldata->lud_scheme); ldap_free_urldesc(urldata); + return false; } @@ -1497,17 +1590,19 @@ parse_hba_auth_opt(char *name, char *val, HbaLine *hbaline, int line_num) hbaline->ldapscope = urldata->lud_scope; if (urldata->lud_filter) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("filters not supported in LDAP URLs"))); + *err_msg = "filters not supported in LDAP URLs"; ldap_free_urldesc(urldata); return false; } ldap_free_urldesc(urldata); #else /* not OpenLDAP */ - ereport(LOG, + ereport(level, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("LDAP URLs not supported on this platform"))); + *err_msg = "LDAP URLs not supported on this platform"; #endif /* not OpenLDAP */ } else if (strcmp(name, "ldaptls") == 0) @@ -1529,11 +1624,12 @@ parse_hba_auth_opt(char *name, char *val, HbaLine *hbaline, int line_num) hbaline->ldapport = atoi(val); if (hbaline->ldapport == 0) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("invalid LDAP port number: \"%s\"", val), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + *err_msg = psprintf("invalid LDAP port number: \"%s\"", val); return false; } } @@ -1617,12 +1713,14 @@ parse_hba_auth_opt(char *name, char *val, HbaLine *hbaline, int line_num) ret = pg_getaddrinfo_all(val, NULL, &hints, &gai_result); if (ret || !gai_result) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("could not translate RADIUS server name \"%s\" to address: %s", val, gai_strerror(ret)), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + *err_msg = psprintf("could not translate RADIUS server name \"%s\" to address: %s", + val, gai_strerror(ret)); if (gai_result) pg_freeaddrinfo_all(hints.ai_family, gai_result); return false; @@ -1636,11 +1734,12 @@ parse_hba_auth_opt(char *name, char *val, HbaLine *hbaline, int line_num) hbaline->radiusport = atoi(val); if (hbaline->radiusport == 0) { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("invalid RADIUS port number: \"%s\"", val), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + *err_msg = psprintf("invalid RADIUS port number: \"%s\"", val); return false; } } @@ -1656,12 +1755,14 @@ parse_hba_auth_opt(char *name, char *val, HbaLine *hbaline, int line_num) } else { - ereport(LOG, + ereport(level, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("unrecognized authentication option name: \"%s\"", name), errcontext("line %d of configuration file \"%s\"", line_num, HbaFileName))); + *err_msg = psprintf("unrecognized authentication option name: \"%s\"", + name); return false; } return true; @@ -1794,7 +1895,7 @@ load_hba(void) return false; } - linecxt = tokenize_file(HbaFileName, file, &hba_lines); + linecxt = tokenize_file(HbaFileName, file, &hba_lines, LOG); FreeFile(file); /* Now parse all the lines */ @@ -1808,7 +1909,7 @@ load_hba(void) TokenizedLine *tok_line = (TokenizedLine *) lfirst(line); HbaLine *newline; - if ((newline = parse_hba_line(tok_line)) == NULL) + if ((newline = parse_hba_line(tok_line, LOG)) == NULL) { /* * Parse error in the file, so indicate there's a problem. NB: a @@ -1878,7 +1979,7 @@ load_hba(void) * NULL. */ static IdentLine * -parse_ident_line(TokenizedLine *tok_line) +parse_ident_line(TokenizedLine * tok_line) { int line_num = tok_line->line_num; ListCell *field; @@ -2170,7 +2271,7 @@ load_ident(void) return false; } - linecxt = tokenize_file(IdentFileName, file, &ident_lines); + linecxt = tokenize_file(IdentFileName, file, &ident_lines, LOG); FreeFile(file); /* Now parse all the lines */ @@ -2261,3 +2362,355 @@ hba_getauthmethod(hbaPort *port) { check_hba(port); } + +/* + * The Macro that specifies the maximum number of authentication options + * that are possible with any given authentication method that is supported. + * Currently LDAP supports 10, The macro value is well above the most any + * method needs + */ +#define MAX_HBA_OPTIONS 12 + +static Datum +gethba_options(HbaLine *hba) +{ + int noptions; + Datum options[MAX_HBA_OPTIONS]; + + noptions = 0; + + if (hba->auth_method == uaGSS || hba->auth_method == uaSSPI) + { + if (hba->include_realm) + options[noptions++] = CStringGetTextDatum("include_realm=true"); + + if (hba->krb_realm) + options[noptions++] = + CStringGetTextDatum(psprintf("krb_realm=%s", hba->krb_realm)); + } + + if (hba->usermap) + options[noptions++] = CStringGetTextDatum(psprintf("map=%s", hba->usermap)); + + if (hba->clientcert) + options[noptions++] = CStringGetTextDatum("clientcert=true"); + + if (hba->pamservice) + options[noptions++] = CStringGetTextDatum(psprintf("pamservice=%s", hba->pamservice)); + + if (hba->auth_method == uaLDAP) + { + if (hba->ldapserver) + options[noptions++] = CStringGetTextDatum(psprintf("ldapserver=%s", hba->ldapserver)); + + if (hba->ldapport) + options[noptions++] = CStringGetTextDatum(psprintf("ldapport=%d", hba->ldapport)); + + if (hba->ldaptls) + options[noptions++] = CStringGetTextDatum("ldaptls=true"); + + if (hba->ldapprefix) + options[noptions++] = CStringGetTextDatum(psprintf("ldapprefix=%s", hba->ldapprefix)); + + if (hba->ldapsuffix) + options[noptions++] = CStringGetTextDatum(psprintf("ldapsuffix=%s", hba->ldapsuffix)); + + if (hba->ldapbasedn) + options[noptions++] = CStringGetTextDatum(psprintf("ldapbasedn=%s", hba->ldapbasedn)); + + if (hba->ldapbinddn) + options[noptions++] = CStringGetTextDatum(psprintf("ldapbinddn=%s", hba->ldapbinddn)); + + if (hba->ldapbindpasswd) + options[noptions++] = CStringGetTextDatum(psprintf("ldapbindpasswd=%s", hba->ldapbindpasswd)); + + if (hba->ldapsearchattribute) + options[noptions++] = CStringGetTextDatum(psprintf("ldapsearchattribute=%s", hba->ldapsearchattribute)); + + if (hba->ldapscope) + options[noptions++] = CStringGetTextDatum(psprintf("ldapscope=%d", hba->ldapscope)); + } + + if (hba->auth_method == uaRADIUS) + { + if (hba->radiusserver) + options[noptions++] = CStringGetTextDatum(psprintf("radiusserver=%s", hba->radiusserver)); + + if (hba->radiussecret) + options[noptions++] = CStringGetTextDatum(psprintf("radiussecret=%s", hba->radiussecret)); + + if (hba->radiusidentifier) + options[noptions++] = CStringGetTextDatum(psprintf("radiusidentifier=%s", hba->radiusidentifier)); + + if (hba->radiusport) + options[noptions++] = CStringGetTextDatum(psprintf("radiusport=%d", hba->radiusport)); + } + + Assert(noptions <= MAX_HBA_OPTIONS); + if (noptions) + return PointerGetDatum( + construct_array(options, noptions, TEXTOID, -1, false, 'i')); + return PointerGetDatum(NULL); +} + +#define NUM_PG_HBA_RULES_ATTS 9 + +static void +fill_hba_line(TupleDesc tupdesc, Tuplestorestate *tuple_store, int lineno, HbaLine *hba, const char *err_msg) +{ + Datum values[NUM_PG_HBA_RULES_ATTS]; + bool nulls[NUM_PG_HBA_RULES_ATTS]; + ListCell *dbcell; + char buffer[NI_MAXHOST]; + HeapTuple tuple; + int index; + Datum options; + + index = 0; + memset(values, 0, sizeof(values)); + memset(nulls, 0, sizeof(nulls)); + + /* line_number */ + values[index] = Int32GetDatum(lineno); + + if (err_msg) + { + /* set all remaining columns as NULL, except error column */ + memset(&nulls[1], true, (NUM_PG_HBA_RULES_ATTS - 2)); + + /* error */ + values[NUM_PG_HBA_RULES_ATTS - 1] = CStringGetTextDatum(err_msg); + } + else + { + /* type */ + index++; + switch (hba->conntype) + { + case ctLocal: + values[index] = CStringGetTextDatum("local"); + break; + case ctHost: + values[index] = CStringGetTextDatum("host"); + break; + case ctHostSSL: + values[index] = CStringGetTextDatum("hostssl"); + break; + case ctHostNoSSL: + values[index] = CStringGetTextDatum("hostnossl"); + break; + } + + /* database */ + index++; + if (hba->databases) + { + List *names = NULL; + HbaToken *tok; + + foreach(dbcell, hba->databases) + { + tok = lfirst(dbcell); + names = lappend(names, tok->string); + } + + /* database */ + Assert(names != NULL); + values[index] = PointerGetDatum(strlist_to_textarray(names)); + } + else + nulls[index] = true; + + /* user */ + index++; + if (hba->roles) + { + List *roles = NULL; + HbaToken *tok; + + foreach(dbcell, hba->roles) + { + tok = lfirst(dbcell); + roles = lappend(roles, tok->string); + } + + /* user */ + Assert(roles != NULL); + values[index] = PointerGetDatum(strlist_to_textarray(roles)); + } + else + nulls[index] = true; + + + /* address */ + index++; + switch (hba->ip_cmp_method) + { + case ipCmpMask: + if (hba->hostname) + { + values[index] = CStringGetTextDatum(hba->hostname); + nulls[++index] = true; + } + else + { + if (pg_getnameinfo_all(&hba->addr, sizeof(struct sockaddr_storage), + buffer, sizeof(buffer), + NULL, 0, + NI_NUMERICHOST) == 0) + { + clean_ipv6_addr(hba->addr.ss_family, buffer); + values[index] = CStringGetTextDatum(buffer); + } + else + nulls[index] = true; + + /* netmask */ + if (pg_getnameinfo_all(&hba->mask, sizeof(struct sockaddr_storage), + buffer, sizeof(buffer), + NULL, 0, + NI_NUMERICHOST) == 0) + { + clean_ipv6_addr(hba->mask.ss_family, buffer); + values[++index] = CStringGetTextDatum(buffer); + } + else + nulls[++index] = true; + } + break; + case ipCmpAll: + values[index] = CStringGetTextDatum("all"); + nulls[++index] = true; + break; + case ipCmpSameHost: + values[index] = CStringGetTextDatum("samehost"); + nulls[++index] = true; + break; + case ipCmpSameNet: + values[index] = CStringGetTextDatum("samenet"); + nulls[++index] = true; + break; + } + + /* auth_method */ + index++; + values[index] = CStringGetTextDatum(UserAuthName[hba->auth_method]); + + /* options */ + index++; + options = gethba_options(hba); + if (options) + values[index] = PointerGetDatum(options); + else + nulls[index] = true; + + /* error */ + index++; + nulls[index] = true; + } + + tuple = heap_form_tuple(tupdesc, values, nulls); + tuplestore_puttuple(tuple_store, tuple); + + return; +} + +/* + * Read the config file and fill the HbaLine records for the view. + */ +static void +fill_hba(TupleDesc tupdesc, Tuplestorestate *tuple_store) +{ + FILE *file; + List *hba_lines = NIL; + ListCell *line; + MemoryContext linecxt; + MemoryContext hbacxt; + MemoryContext oldcxt; + + file = AllocateFile(HbaFileName, "r"); + if (file == NULL) + { + ereport(ERROR, + (errcode_for_file_access(), + errmsg("could not open configuration file \"%s\": %m", + HbaFileName))); + return; + } + + linecxt = tokenize_file(HbaFileName, file, &hba_lines, DEBUG3); + FreeFile(file); + + /* Now parse all the lines */ + hbacxt = AllocSetContextCreate(CurrentMemoryContext, + "hba parser context", + ALLOCSET_SMALL_SIZES); + oldcxt = MemoryContextSwitchTo(hbacxt); + foreach(line, hba_lines) + { + TokenizedLine *tok_line = (TokenizedLine *) lfirst(line); + HbaLine *newline = NULL; + + if (tok_line->err_msg == NULL) + newline = parse_hba_line(tok_line, DEBUG3); + + fill_hba_line(tupdesc, tuple_store, tok_line->line_num, newline, tok_line->err_msg); + } + + /* Free tokenizer memory */ + MemoryContextDelete(linecxt); + MemoryContextSwitchTo(oldcxt); + MemoryContextDelete(hbacxt); +} + +/* + * SQL-accessible SRF to return all the settings from the pg_hba.conf + * file. + */ +Datum +hba_rules(PG_FUNCTION_ARGS) +{ + Tuplestorestate *tuple_store; + TupleDesc tupdesc; + MemoryContext old_cxt; + ReturnSetInfo *rsi; + + /* + * We must use the Materialize mode to be safe against HBA file reloads + * while the cursor is open. It's also more efficient than having to look + * up our current position in the parsed list every time. + */ + rsi = (ReturnSetInfo *) fcinfo->resultinfo; + + /* Check to see if caller supports us returning a tuplestore */ + if (rsi == NULL || !IsA(rsi, ReturnSetInfo)) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("set-valued function called in context that cannot accept a set"))); + if (!(rsi->allowedModes & SFRM_Materialize)) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("materialize mode required, but it is not " \ + "allowed in this context"))); + + rsi->returnMode = SFRM_Materialize; + + /* Build a tuple descriptor for our result type */ + if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE) + elog(ERROR, "return type must be a row type"); + + /* Build tuplestore to hold the result rows */ + old_cxt = MemoryContextSwitchTo(rsi->econtext->ecxt_per_query_memory); + + tuple_store = + tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random, + false, work_mem); + rsi->setDesc = tupdesc; + rsi->setResult = tuple_store; + + MemoryContextSwitchTo(old_cxt); + + fill_hba(tupdesc, tuple_store); + + PG_RETURN_NULL(); +} diff --git a/src/include/catalog/pg_proc.h b/src/include/catalog/pg_proc.h index 31c828a..90d61d9 100644 --- a/src/include/catalog/pg_proc.h +++ b/src/include/catalog/pg_proc.h @@ -3076,6 +3076,8 @@ DATA(insert OID = 2084 ( pg_show_all_settings PGNSP PGUID 12 1 1000 0 0 f f f f DESCR("SHOW ALL as a function"); DATA(insert OID = 3329 ( pg_show_all_file_settings PGNSP PGUID 12 1 1000 0 0 f f f f t t v s 0 0 2249 "" "{25,23,23,25,25,16,25}" "{o,o,o,o,o,o,o}" "{sourcefile,sourceline,seqno,name,setting,applied,error}" _null_ _null_ show_all_file_settings _null_ _null_ _null_ )); DESCR("show config file settings"); +DATA(insert OID = 3401 ( pg_hba_rules PGNSP PGUID 12 1 1000 0 0 f f f f t t v s 0 0 2249 "" "{23,25,1009,1009,25,25,25,1009,25}" "{o,o,o,o,o,o,o,o,o}" "{line_number,type,database,user_name,address,netmask,auth_method,options,error}" _null_ _null_ hba_rules _null_ _null_ _null_ )); +DESCR("show pg_hba config rules"); DATA(insert OID = 1371 ( pg_lock_status PGNSP PGUID 12 1 1000 0 0 f f f f t t v s 0 0 2249 "" "{25,26,26,23,21,25,28,26,26,21,25,23,25,16,16}" "{o,o,o,o,o,o,o,o,o,o,o,o,o,o,o}" "{locktype,database,relation,page,tuple,virtualxid,transactionid,classid,objid,objsubid,virtualtransaction,pid,mode,granted,fastpath}" _null_ _null_ pg_lock_status _null_ _null_ _null_ )); DESCR("view system lock information"); DATA(insert OID = 2561 ( pg_blocking_pids PGNSP PGUID 12 1 0 0 0 f f f f t f v s 1 0 1007 "23" _null_ _null_ _null_ _null_ _null_ pg_blocking_pids _null_ _null_ _null_ )); diff --git a/src/include/libpq/hba.h b/src/include/libpq/hba.h index dc7d257..c936308 100644 --- a/src/include/libpq/hba.h +++ b/src/include/libpq/hba.h @@ -15,11 +15,17 @@ #include "nodes/pg_list.h" #include "regex/regex.h" - +/* + * The following enum represents the authentication methods that + * are supported by PostgreSQL. + * + * NOTE: Any additions in this enum must update the UserAuthName array to be + * in sync. + */ typedef enum UserAuth { uaReject, - uaImplicitReject, + uaImplicitReject, /* Not user visibile option */ uaTrust, uaIdent, uaPassword, diff --git a/src/test/regress/expected/rules.out b/src/test/regress/expected/rules.out index 60abcad..de7860a 100644 --- a/src/test/regress/expected/rules.out +++ b/src/test/regress/expected/rules.out @@ -1338,6 +1338,16 @@ pg_group| SELECT pg_authid.rolname AS groname, WHERE (pg_auth_members.roleid = pg_authid.oid)) AS grolist FROM pg_authid WHERE (NOT pg_authid.rolcanlogin); +pg_hba_rules| SELECT a.line_number, + a.type, + a.database, + a.user_name, + a.address, + a.netmask, + a.auth_method, + a.options, + a.error + FROM pg_hba_rules() a(line_number, type, database, user_name, address, netmask, auth_method, options, error); pg_indexes| SELECT n.nspname AS schemaname, c.relname AS tablename, i.relname AS indexname,