PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
hba.c File Reference
#include "postgres.h"
#include <ctype.h>
#include <pwd.h>
#include <fcntl.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "access/htup_details.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 "utils/acl.h"
#include "utils/builtins.h"
#include "utils/varlena.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
Include dependency graph for hba.c:

Go to the source code of this file.

Data Structures

struct  check_network_data
 
struct  HbaToken
 
struct  TokenizedLine
 

Macros

#define MAX_TOKEN   256
 
#define MAX_LINE   8192
 
#define token_is_keyword(t, k)   (!t->quoted && strcmp(t->string, k) == 0)
 
#define token_matches(t, k)   (strcmp(t->string, k) == 0)
 
#define INVALID_AUTH_OPTION(optname, validmethods)
 
#define REQUIRE_AUTH_OPTION(methodval, optname, validmethods)
 
#define MANDATORY_AUTH_ARG(argvar, argname, authname)
 
#define IDENT_FIELD_ABSENT(field)
 
#define IDENT_MULTI_VALUE(tokens)
 
#define MAX_HBA_OPTIONS   12
 
#define NUM_PG_HBA_FILE_RULES_ATTS   9
 

Typedefs

typedef struct check_network_data check_network_data
 
typedef struct HbaToken HbaToken
 
typedef struct TokenizedLine TokenizedLine
 

Functions

static MemoryContext tokenize_file (const char *filename, FILE *file, List **tok_lines, int elevel)
 
static Listtokenize_inc_file (List *tokens, const char *outer_filename, const char *inc_filename, int elevel, char **err_msg)
 
static bool parse_hba_auth_opt (char *name, char *val, HbaLine *hbaline, int elevel, char **err_msg)
 
static bool verify_option_list_length (List *options, char *optionname, List *masters, char *mastername, int line_num)
 
static ArrayTypegethba_options (HbaLine *hba)
 
static void fill_hba_line (Tuplestorestate *tuple_store, TupleDesc tupdesc, int lineno, HbaLine *hba, const char *err_msg)
 
static void fill_hba_view (Tuplestorestate *tuple_store, TupleDesc tupdesc)
 
bool pg_isblank (const char c)
 
static bool next_token (char **lineptr, char *buf, int bufsz, bool *initial_quote, bool *terminating_comma, int elevel, char **err_msg)
 
static HbaTokenmake_hba_token (const char *token, bool quoted)
 
static HbaTokencopy_hba_token (HbaToken *in)
 
static Listnext_field_expand (const char *filename, char **lineptr, int elevel, char **err_msg)
 
static bool is_member (Oid userid, const char *role)
 
static bool check_role (const char *role, Oid roleid, List *tokens)
 
static bool check_db (const char *dbname, const char *role, Oid roleid, List *tokens)
 
static bool ipv4eq (struct sockaddr_in *a, struct sockaddr_in *b)
 
static bool hostname_match (const char *pattern, const char *actual_hostname)
 
static bool check_hostname (hbaPort *port, const char *hostname)
 
static bool check_ip (SockAddr *raddr, struct sockaddr *addr, struct sockaddr *mask)
 
static void check_network_callback (struct sockaddr *addr, struct sockaddr *netmask, void *cb_data)
 
static bool check_same_host_or_net (SockAddr *raddr, IPCompareMethod method)
 
static HbaLineparse_hba_line (TokenizedLine *tok_line, int elevel)
 
static void check_hba (hbaPort *port)
 
bool load_hba (void)
 
Datum pg_hba_file_rules (PG_FUNCTION_ARGS)
 
static IdentLineparse_ident_line (TokenizedLine *tok_line)
 
static void check_ident_usermap (IdentLine *identLine, const char *usermap_name, const char *pg_role, const char *ident_user, bool case_insensitive, bool *found_p, bool *error_p)
 
int check_usermap (const char *usermap_name, const char *pg_role, const char *auth_user, bool case_insensitive)
 
bool load_ident (void)
 
void hba_getauthmethod (hbaPort *port)
 

Variables

static Listparsed_hba_lines = NIL
 
static MemoryContext parsed_hba_context = NULL
 
static Listparsed_ident_lines = NIL
 
static MemoryContext parsed_ident_context = NULL
 
static const char *const UserAuthName []
 

Macro Definition Documentation

#define IDENT_FIELD_ABSENT (   field)
Value:
do { \
if (!field) { \
(errcode(ERRCODE_CONFIG_FILE_ERROR), \
errmsg("missing entry in file \"%s\" at end of line %d", \
IdentFileName, line_num))); \
return NULL; \
} \
} while (0)
int errcode(int sqlerrcode)
Definition: elog.c:575
#define LOG
Definition: elog.h:26
char * IdentFileName
Definition: guc.c:464
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797

Definition at line 908 of file hba.c.

Referenced by parse_ident_line().

#define IDENT_MULTI_VALUE (   tokens)
Value:
do { \
if (tokens->length > 1) { \
(errcode(ERRCODE_CONFIG_FILE_ERROR), \
errmsg("multiple values in ident field"), \
errcontext("line %d of configuration file \"%s\"", \
line_num, IdentFileName))); \
return NULL; \
} \
} while (0)
int errcode(int sqlerrcode)
Definition: elog.c:575
#define LOG
Definition: elog.h:26
char * IdentFileName
Definition: guc.c:464
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define errcontext
Definition: elog.h:164

Definition at line 919 of file hba.c.

Referenced by parse_ident_line().

#define INVALID_AUTH_OPTION (   optname,
  validmethods 
)
Value:
do { \
(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)
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
int errcode(int sqlerrcode)
Definition: elog.c:575
char * HbaFileName
Definition: guc.c:463
#define ereport(elevel, rest)
Definition: elog.h:122
static int elevel
Definition: vacuumlazy.c:136
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define errcontext
Definition: elog.h:164
#define _(x)
Definition: elog.c:84

Definition at line 860 of file hba.c.

Referenced by parse_hba_auth_opt().

#define MANDATORY_AUTH_ARG (   argvar,
  argname,
  authname 
)
Value:
do { \
if (argvar == NULL) { \
(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))); \
*err_msg = psprintf("authentication method \"%s\" requires argument \"%s\" to be set", \
authname, argname); \
return NULL; \
} \
} while (0)
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
int errcode(int sqlerrcode)
Definition: elog.c:575
char * HbaFileName
Definition: guc.c:463
#define ereport(elevel, rest)
Definition: elog.h:122
static int elevel
Definition: vacuumlazy.c:136
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define errcontext
Definition: elog.h:164

Definition at line 880 of file hba.c.

Referenced by parse_hba_line().

#define MAX_HBA_OPTIONS   12

Definition at line 2208 of file hba.c.

Referenced by gethba_options().

#define MAX_LINE   8192

Definition at line 57 of file hba.c.

Referenced by tokenize_file().

#define MAX_TOKEN   256

Definition at line 56 of file hba.c.

Referenced by next_field_expand().

#define NUM_PG_HBA_FILE_RULES_ATTS   9

Definition at line 2323 of file hba.c.

Referenced by fill_hba_line().

#define REQUIRE_AUTH_OPTION (   methodval,
  optname,
  validmethods 
)
Value:
do { \
if (hbaline->auth_method != methodval) \
INVALID_AUTH_OPTION(optname, validmethods); \
} while (0)
#define INVALID_AUTH_OPTION(optname, validmethods)
Definition: hba.c:860

Definition at line 874 of file hba.c.

Referenced by parse_hba_auth_opt().

#define token_is_keyword (   t,
 
)    (!t->quoted && strcmp(t->string, k) == 0)

Definition at line 68 of file hba.c.

Referenced by check_db(), check_role(), and parse_hba_line().

#define token_matches (   t,
 
)    (strcmp(t->string, k) == 0)

Definition at line 69 of file hba.c.

Referenced by check_db(), and check_role().

Typedef Documentation

Function Documentation

static bool check_db ( const char *  dbname,
const char *  role,
Oid  roleid,
List tokens 
)
static

Definition at line 610 of file hba.c.

References am_db_walsender, am_walsender, is_member(), lfirst, token_is_keyword, and token_matches.

Referenced by check_hba().

611 {
612  ListCell *cell;
613  HbaToken *tok;
614 
615  foreach(cell, tokens)
616  {
617  tok = lfirst(cell);
619  {
620  /*
621  * physical replication walsender connections can only match
622  * replication keyword
623  */
624  if (token_is_keyword(tok, "replication"))
625  return true;
626  }
627  else if (token_is_keyword(tok, "all"))
628  return true;
629  else if (token_is_keyword(tok, "sameuser"))
630  {
631  if (strcmp(dbname, role) == 0)
632  return true;
633  }
634  else if (token_is_keyword(tok, "samegroup") ||
635  token_is_keyword(tok, "samerole"))
636  {
637  if (is_member(roleid, dbname))
638  return true;
639  }
640  else if (token_is_keyword(tok, "replication"))
641  continue; /* never match this if not walsender */
642  else if (token_matches(tok, dbname))
643  return true;
644  }
645  return false;
646 }
#define token_matches(t, k)
Definition: hba.c:69
bool am_walsender
Definition: walsender.c:114
Definition: hba.c:75
bool am_db_walsender
Definition: walsender.c:117
#define lfirst(lc)
Definition: pg_list.h:106
char * dbname
Definition: streamutil.c:45
static bool is_member(Oid userid, const char *role)
Definition: hba.c:562
#define token_is_keyword(t, k)
Definition: hba.c:68
static void check_hba ( hbaPort port)
static

Definition at line 2009 of file hba.c.

References SockAddr::addr, HbaLine::addr, HbaLine::auth_method, check_db(), check_hostname(), check_ip(), check_role(), check_same_host_or_net(), HbaLine::conntype, ctHostNoSSL, ctHostSSL, ctLocal, Port::database_name, HbaLine::databases, get_role_oid(), Port::hba, HbaLine::hostname, HbaLine::ip_cmp_method, ipCmpAll, ipCmpMask, ipCmpSameHost, ipCmpSameNet, IS_AF_UNIX, lfirst, HbaLine::mask, palloc0(), Port::raddr, HbaLine::roles, Port::ssl_in_use, uaImplicitReject, and Port::user_name.

Referenced by hba_getauthmethod().

2010 {
2011  Oid roleid;
2012  ListCell *line;
2013  HbaLine *hba;
2014 
2015  /* Get the target role's OID. Note we do not error out for bad role. */
2016  roleid = get_role_oid(port->user_name, true);
2017 
2018  foreach(line, parsed_hba_lines)
2019  {
2020  hba = (HbaLine *) lfirst(line);
2021 
2022  /* Check connection type */
2023  if (hba->conntype == ctLocal)
2024  {
2025  if (!IS_AF_UNIX(port->raddr.addr.ss_family))
2026  continue;
2027  }
2028  else
2029  {
2030  if (IS_AF_UNIX(port->raddr.addr.ss_family))
2031  continue;
2032 
2033  /* Check SSL state */
2034  if (port->ssl_in_use)
2035  {
2036  /* Connection is SSL, match both "host" and "hostssl" */
2037  if (hba->conntype == ctHostNoSSL)
2038  continue;
2039  }
2040  else
2041  {
2042  /* Connection is not SSL, match both "host" and "hostnossl" */
2043  if (hba->conntype == ctHostSSL)
2044  continue;
2045  }
2046 
2047  /* Check IP address */
2048  switch (hba->ip_cmp_method)
2049  {
2050  case ipCmpMask:
2051  if (hba->hostname)
2052  {
2053  if (!check_hostname(port,
2054  hba->hostname))
2055  continue;
2056  }
2057  else
2058  {
2059  if (!check_ip(&port->raddr,
2060  (struct sockaddr *) &hba->addr,
2061  (struct sockaddr *) &hba->mask))
2062  continue;
2063  }
2064  break;
2065  case ipCmpAll:
2066  break;
2067  case ipCmpSameHost:
2068  case ipCmpSameNet:
2069  if (!check_same_host_or_net(&port->raddr,
2070  hba->ip_cmp_method))
2071  continue;
2072  break;
2073  default:
2074  /* shouldn't get here, but deem it no-match if so */
2075  continue;
2076  }
2077  } /* != ctLocal */
2078 
2079  /* Check database and role */
2080  if (!check_db(port->database_name, port->user_name, roleid,
2081  hba->databases))
2082  continue;
2083 
2084  if (!check_role(port->user_name, roleid, hba->roles))
2085  continue;
2086 
2087  /* Found a record that matched! */
2088  port->hba = hba;
2089  return;
2090  }
2091 
2092  /* If no matching entry was found, then implicitly reject. */
2093  hba = palloc0(sizeof(HbaLine));
2095  port->hba = hba;
2096 }
List * databases
Definition: hba.h:66
Definition: hba.h:61
struct sockaddr_storage mask
Definition: hba.h:69
Definition: hba.h:47
struct sockaddr_storage addr
Definition: pqcomm.h:64
bool ssl_in_use
Definition: libpq-be.h:181
unsigned int Oid
Definition: postgres_ext.h:31
static bool check_hostname(hbaPort *port, const char *hostname)
Definition: hba.c:693
static List * parsed_hba_lines
Definition: hba.c:101
Oid get_role_oid(const char *rolname, bool missing_ok)
Definition: acl.c:5111
SockAddr raddr
Definition: libpq-be.h:122
ConnType conntype
Definition: hba.h:65
Definition: hba.h:57
struct sockaddr_storage addr
Definition: hba.h:68
#define IS_AF_UNIX(fam)
Definition: ip.h:24
static bool check_ip(SockAddr *raddr, struct sockaddr *addr, struct sockaddr *mask)
Definition: hba.c:786
char * user_name
Definition: libpq-be.h:137
static bool check_role(const char *role, Oid roleid, List *tokens)
Definition: hba.c:586
Definition: hba.h:55
HbaLine * hba
Definition: libpq-be.h:144
Definition: hba.h:50
void * palloc0(Size size)
Definition: mcxt.c:877
char * hostname
Definition: hba.h:71
List * roles
Definition: hba.h:67
#define lfirst(lc)
Definition: pg_list.h:106
static bool check_db(const char *dbname, const char *role, Oid roleid, List *tokens)
Definition: hba.c:610
static bool check_same_host_or_net(SockAddr *raddr, IPCompareMethod method)
Definition: hba.c:827
IPCompareMethod ip_cmp_method
Definition: hba.h:70
char * database_name
Definition: libpq-be.h:136
UserAuth auth_method
Definition: hba.h:72
static bool check_hostname ( hbaPort port,
const char *  hostname 
)
static

Definition at line 693 of file hba.c.

References SockAddr::addr, addrinfo::ai_addr, addrinfo::ai_next, DEBUG2, elog, freeaddrinfo, getaddrinfo, hostname_match(), ipv4eq(), NI_MAXHOST, NI_NAMEREQD, pg_getnameinfo_all(), pstrdup(), Port::raddr, Port::remote_hostname, Port::remote_hostname_errcode, Port::remote_hostname_resolv, and SockAddr::salen.

Referenced by check_hba().

694 {
695  struct addrinfo *gai_result,
696  *gai;
697  int ret;
698  bool found;
699 
700  /* Quick out if remote host name already known bad */
701  if (port->remote_hostname_resolv < 0)
702  return false;
703 
704  /* Lookup remote host name if not already done */
705  if (!port->remote_hostname)
706  {
707  char remote_hostname[NI_MAXHOST];
708 
709  ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
710  remote_hostname, sizeof(remote_hostname),
711  NULL, 0,
712  NI_NAMEREQD);
713  if (ret != 0)
714  {
715  /* remember failure; don't complain in the postmaster log yet */
716  port->remote_hostname_resolv = -2;
717  port->remote_hostname_errcode = ret;
718  return false;
719  }
720 
721  port->remote_hostname = pstrdup(remote_hostname);
722  }
723 
724  /* Now see if remote host name matches this pg_hba line */
726  return false;
727 
728  /* If we already verified the forward lookup, we're done */
729  if (port->remote_hostname_resolv == +1)
730  return true;
731 
732  /* Lookup IP from host name and check against original IP */
733  ret = getaddrinfo(port->remote_hostname, NULL, NULL, &gai_result);
734  if (ret != 0)
735  {
736  /* remember failure; don't complain in the postmaster log yet */
737  port->remote_hostname_resolv = -2;
738  port->remote_hostname_errcode = ret;
739  return false;
740  }
741 
742  found = false;
743  for (gai = gai_result; gai; gai = gai->ai_next)
744  {
745  if (gai->ai_addr->sa_family == port->raddr.addr.ss_family)
746  {
747  if (gai->ai_addr->sa_family == AF_INET)
748  {
749  if (ipv4eq((struct sockaddr_in *) gai->ai_addr,
750  (struct sockaddr_in *) &port->raddr.addr))
751  {
752  found = true;
753  break;
754  }
755  }
756 #ifdef HAVE_IPV6
757  else if (gai->ai_addr->sa_family == AF_INET6)
758  {
759  if (ipv6eq((struct sockaddr_in6 *) gai->ai_addr,
760  (struct sockaddr_in6 *) &port->raddr.addr))
761  {
762  found = true;
763  break;
764  }
765  }
766 #endif
767  }
768  }
769 
770  if (gai_result)
771  freeaddrinfo(gai_result);
772 
773  if (!found)
774  elog(DEBUG2, "pg_hba.conf host name \"%s\" rejected because address resolution did not return a match with IP address of client",
775  hostname);
776 
777  port->remote_hostname_resolv = found ? +1 : -1;
778 
779  return found;
780 }
#define getaddrinfo
Definition: getaddrinfo.h:136
#define NI_NAMEREQD
Definition: getaddrinfo.h:84
char * pstrdup(const char *in)
Definition: mcxt.c:1076
#define freeaddrinfo
Definition: getaddrinfo.h:141
struct sockaddr_storage addr
Definition: pqcomm.h:64
static bool ipv4eq(struct sockaddr_in *a, struct sockaddr_in *b)
Definition: hba.c:649
char * remote_hostname
Definition: libpq-be.h:124
SockAddr raddr
Definition: libpq-be.h:122
#define NI_MAXHOST
Definition: getaddrinfo.h:88
static bool hostname_match(const char *pattern, const char *actual_hostname)
Definition: hba.c:673
#define DEBUG2
Definition: elog.h:24
int remote_hostname_errcode
Definition: libpq-be.h:127
ACCEPT_TYPE_ARG3 salen
Definition: pqcomm.h:65
int pg_getnameinfo_all(const struct sockaddr_storage *addr, int salen, char *node, int nodelen, char *service, int servicelen, int flags)
Definition: ip.c:122
int remote_hostname_resolv
Definition: libpq-be.h:126
struct addrinfo * ai_next
Definition: getaddrinfo.h:107
#define elog
Definition: elog.h:219
static char * hostname
Definition: pg_regress.c:88
struct sockaddr * ai_addr
Definition: getaddrinfo.h:105
static void check_ident_usermap ( IdentLine identLine,
const char *  usermap_name,
const char *  pg_role,
const char *  ident_user,
bool  case_insensitive,
bool found_p,
bool error_p 
)
static

Definition at line 2706 of file hba.c.

References ereport, errcode(), errmsg(), IdentLine::ident_user, LOG, palloc(), palloc0(), pfree(), pg_mb2wchar_with_len(), pg_regerror(), pg_regexec(), IdentLine::pg_role, pg_strcasecmp(), pstrdup(), IdentLine::re, REG_NOMATCH, regmatch_t::rm_eo, regmatch_t::rm_so, and IdentLine::usermap.

Referenced by check_usermap().

2709 {
2710  *found_p = false;
2711  *error_p = false;
2712 
2713  if (strcmp(identLine->usermap, usermap_name) != 0)
2714  /* Line does not match the map name we're looking for, so just abort */
2715  return;
2716 
2717  /* Match? */
2718  if (identLine->ident_user[0] == '/')
2719  {
2720  /*
2721  * When system username starts with a slash, treat it as a regular
2722  * expression. In this case, we process the system username as a
2723  * regular expression that returns exactly one match. This is replaced
2724  * for \1 in the database username string, if present.
2725  */
2726  int r;
2727  regmatch_t matches[2];
2728  pg_wchar *wstr;
2729  int wlen;
2730  char *ofs;
2731  char *regexp_pgrole;
2732 
2733  wstr = palloc((strlen(ident_user) + 1) * sizeof(pg_wchar));
2734  wlen = pg_mb2wchar_with_len(ident_user, wstr, strlen(ident_user));
2735 
2736  r = pg_regexec(&identLine->re, wstr, wlen, 0, NULL, 2, matches, 0);
2737  if (r)
2738  {
2739  char errstr[100];
2740 
2741  if (r != REG_NOMATCH)
2742  {
2743  /* REG_NOMATCH is not an error, everything else is */
2744  pg_regerror(r, &identLine->re, errstr, sizeof(errstr));
2745  ereport(LOG,
2746  (errcode(ERRCODE_INVALID_REGULAR_EXPRESSION),
2747  errmsg("regular expression match for \"%s\" failed: %s",
2748  identLine->ident_user + 1, errstr)));
2749  *error_p = true;
2750  }
2751 
2752  pfree(wstr);
2753  return;
2754  }
2755  pfree(wstr);
2756 
2757  if ((ofs = strstr(identLine->pg_role, "\\1")) != NULL)
2758  {
2759  int offset;
2760 
2761  /* substitution of the first argument requested */
2762  if (matches[1].rm_so < 0)
2763  {
2764  ereport(LOG,
2765  (errcode(ERRCODE_INVALID_REGULAR_EXPRESSION),
2766  errmsg("regular expression \"%s\" has no subexpressions as requested by backreference in \"%s\"",
2767  identLine->ident_user + 1, identLine->pg_role)));
2768  *error_p = true;
2769  return;
2770  }
2771 
2772  /*
2773  * length: original length minus length of \1 plus length of match
2774  * plus null terminator
2775  */
2776  regexp_pgrole = palloc0(strlen(identLine->pg_role) - 2 + (matches[1].rm_eo - matches[1].rm_so) + 1);
2777  offset = ofs - identLine->pg_role;
2778  memcpy(regexp_pgrole, identLine->pg_role, offset);
2779  memcpy(regexp_pgrole + offset,
2780  ident_user + matches[1].rm_so,
2781  matches[1].rm_eo - matches[1].rm_so);
2782  strcat(regexp_pgrole, ofs + 2);
2783  }
2784  else
2785  {
2786  /* no substitution, so copy the match */
2787  regexp_pgrole = pstrdup(identLine->pg_role);
2788  }
2789 
2790  /*
2791  * now check if the username actually matched what the user is trying
2792  * to connect as
2793  */
2794  if (case_insensitive)
2795  {
2796  if (pg_strcasecmp(regexp_pgrole, pg_role) == 0)
2797  *found_p = true;
2798  }
2799  else
2800  {
2801  if (strcmp(regexp_pgrole, pg_role) == 0)
2802  *found_p = true;
2803  }
2804  pfree(regexp_pgrole);
2805 
2806  return;
2807  }
2808  else
2809  {
2810  /* Not regular expression, so make complete match */
2811  if (case_insensitive)
2812  {
2813  if (pg_strcasecmp(identLine->pg_role, pg_role) == 0 &&
2814  pg_strcasecmp(identLine->ident_user, ident_user) == 0)
2815  *found_p = true;
2816  }
2817  else
2818  {
2819  if (strcmp(identLine->pg_role, pg_role) == 0 &&
2820  strcmp(identLine->ident_user, ident_user) == 0)
2821  *found_p = true;
2822  }
2823  }
2824  return;
2825 }
regex_t re
Definition: hba.h:110
char * pstrdup(const char *in)
Definition: mcxt.c:1076
regoff_t rm_so
Definition: regex.h:85
int errcode(int sqlerrcode)
Definition: elog.c:575
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define LOG
Definition: elog.h:26
regoff_t rm_eo
Definition: regex.h:86
void pfree(void *pointer)
Definition: mcxt.c:949
char * usermap
Definition: hba.h:107
size_t pg_regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)
Definition: regerror.c:60
#define ereport(elevel, rest)
Definition: elog.h:122
unsigned int pg_wchar
Definition: mbprint.c:31
void * palloc0(Size size)
Definition: mcxt.c:877
int pg_mb2wchar_with_len(const char *from, pg_wchar *to, int len)
Definition: mbutils.c:734
char * ident_user
Definition: hba.h:108
int pg_regexec(regex_t *re, const chr *string, size_t len, size_t search_start, rm_detail_t *details, size_t nmatch, regmatch_t pmatch[], int flags)
Definition: regexec.c:172
void * palloc(Size size)
Definition: mcxt.c:848
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define REG_NOMATCH
Definition: regex.h:138
char * pg_role
Definition: hba.h:109
static bool check_ip ( SockAddr raddr,
struct sockaddr *  addr,
struct sockaddr *  mask 
)
static

Definition at line 786 of file hba.c.

References SockAddr::addr, and pg_range_sockaddr().

Referenced by check_hba(), and check_network_callback().

787 {
788  if (raddr->addr.ss_family == addr->sa_family &&
789  pg_range_sockaddr(&raddr->addr,
790  (struct sockaddr_storage *) addr,
791  (struct sockaddr_storage *) mask))
792  return true;
793  return false;
794 }
struct sockaddr_storage addr
Definition: pqcomm.h:64
int pg_range_sockaddr(const struct sockaddr_storage *addr, const struct sockaddr_storage *netaddr, const struct sockaddr_storage *netmask)
Definition: ifaddr.c:53
static void check_network_callback ( struct sockaddr *  addr,
struct sockaddr *  netmask,
void *  cb_data 
)
static

Definition at line 800 of file hba.c.

References check_ip(), ipCmpSameHost, check_network_data::method, pg_sockaddr_cidr_mask(), check_network_data::raddr, and check_network_data::result.

Referenced by check_same_host_or_net().

802 {
803  check_network_data *cn = (check_network_data *) cb_data;
804  struct sockaddr_storage mask;
805 
806  /* Already found a match? */
807  if (cn->result)
808  return;
809 
810  if (cn->method == ipCmpSameHost)
811  {
812  /* Make an all-ones netmask of appropriate length for family */
813  pg_sockaddr_cidr_mask(&mask, NULL, addr->sa_family);
814  cn->result = check_ip(cn->raddr, addr, (struct sockaddr *) &mask);
815  }
816  else
817  {
818  /* Use the netmask of the interface itself */
819  cn->result = check_ip(cn->raddr, addr, netmask);
820  }
821 }
SockAddr * raddr
Definition: hba.c:63
IPCompareMethod method
Definition: hba.c:62
int pg_sockaddr_cidr_mask(struct sockaddr_storage *mask, char *numbits, int family)
Definition: ifaddr.c:115
static bool check_ip(SockAddr *raddr, struct sockaddr *addr, struct sockaddr *mask)
Definition: hba.c:786
bool result
Definition: hba.c:64
static bool check_role ( const char *  role,
Oid  roleid,
List tokens 
)
static

Definition at line 586 of file hba.c.

References is_member(), lfirst, HbaToken::quoted, HbaToken::string, token_is_keyword, and token_matches.

Referenced by check_hba().

587 {
588  ListCell *cell;
589  HbaToken *tok;
590 
591  foreach(cell, tokens)
592  {
593  tok = lfirst(cell);
594  if (!tok->quoted && tok->string[0] == '+')
595  {
596  if (is_member(roleid, tok->string + 1))
597  return true;
598  }
599  else if (token_matches(tok, role) ||
600  token_is_keyword(tok, "all"))
601  return true;
602  }
603  return false;
604 }
#define token_matches(t, k)
Definition: hba.c:69
Definition: hba.c:75
char * string
Definition: hba.c:77
bool quoted
Definition: hba.c:78
#define lfirst(lc)
Definition: pg_list.h:106
static bool is_member(Oid userid, const char *role)
Definition: hba.c:562
#define token_is_keyword(t, k)
Definition: hba.c:68
static bool check_same_host_or_net ( SockAddr raddr,
IPCompareMethod  method 
)
static

Definition at line 827 of file hba.c.

References check_network_callback(), elog, LOG, check_network_data::method, pg_foreach_ifaddr(), check_network_data::raddr, and check_network_data::result.

Referenced by check_hba().

828 {
830 
831  cn.method = method;
832  cn.raddr = raddr;
833  cn.result = false;
834 
835  errno = 0;
837  {
838  elog(LOG, "error enumerating network interfaces: %m");
839  return false;
840  }
841 
842  return cn.result;
843 }
SockAddr * raddr
Definition: hba.c:63
#define LOG
Definition: elog.h:26
IPCompareMethod method
Definition: hba.c:62
int pg_foreach_ifaddr(PgIfAddrCallback callback, void *cb_data)
Definition: ifaddr.c:559
static void check_network_callback(struct sockaddr *addr, struct sockaddr *netmask, void *cb_data)
Definition: hba.c:800
bool result
Definition: hba.c:64
#define elog
Definition: elog.h:219
int check_usermap ( const char *  usermap_name,
const char *  pg_role,
const char *  auth_user,
bool  case_insensitive 
)

Definition at line 2842 of file hba.c.

References check_ident_usermap(), ereport, errmsg(), error(), lfirst, LOG, pg_strcasecmp(), STATUS_ERROR, and STATUS_OK.

Referenced by ident_inet().

2846 {
2847  bool found_entry = false,
2848  error = false;
2849 
2850  if (usermap_name == NULL || usermap_name[0] == '\0')
2851  {
2852  if (case_insensitive)
2853  {
2854  if (pg_strcasecmp(pg_role, auth_user) == 0)
2855  return STATUS_OK;
2856  }
2857  else
2858  {
2859  if (strcmp(pg_role, auth_user) == 0)
2860  return STATUS_OK;
2861  }
2862  ereport(LOG,
2863  (errmsg("provided user name (%s) and authenticated user name (%s) do not match",
2864  pg_role, auth_user)));
2865  return STATUS_ERROR;
2866  }
2867  else
2868  {
2869  ListCell *line_cell;
2870 
2871  foreach(line_cell, parsed_ident_lines)
2872  {
2873  check_ident_usermap(lfirst(line_cell), usermap_name,
2874  pg_role, auth_user, case_insensitive,
2875  &found_entry, &error);
2876  if (found_entry || error)
2877  break;
2878  }
2879  }
2880  if (!found_entry && !error)
2881  {
2882  ereport(LOG,
2883  (errmsg("no match in usermap \"%s\" for user \"%s\" authenticated as \"%s\"",
2884  usermap_name, pg_role, auth_user)));
2885  }
2886  return found_entry ? STATUS_OK : STATUS_ERROR;
2887 }
static void check_ident_usermap(IdentLine *identLine, const char *usermap_name, const char *pg_role, const char *ident_user, bool case_insensitive, bool *found_p, bool *error_p)
Definition: hba.c:2706
static void error(void)
Definition: sql-dyntest.c:147
#define STATUS_ERROR
Definition: c.h:965
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define LOG
Definition: elog.h:26
#define ereport(elevel, rest)
Definition: elog.h:122
#define STATUS_OK
Definition: c.h:964
static List * parsed_ident_lines
Definition: hba.c:112
#define lfirst(lc)
Definition: pg_list.h:106
int errmsg(const char *fmt,...)
Definition: elog.c:797
static HbaToken* copy_hba_token ( HbaToken in)
static

Definition at line 307 of file hba.c.

References make_hba_token(), HbaToken::quoted, and HbaToken::string.

Referenced by parse_hba_line(), and tokenize_inc_file().

308 {
309  HbaToken *out = make_hba_token(in->string, in->quoted);
310 
311  return out;
312 }
Definition: hba.c:75
char * string
Definition: hba.c:77
bool quoted
Definition: hba.c:78
static HbaToken * make_hba_token(const char *token, bool quoted)
Definition: hba.c:288
static void fill_hba_line ( Tuplestorestate tuple_store,
TupleDesc  tupdesc,
int  lineno,
HbaLine hba,
const char *  err_msg 
)
static

Definition at line 2338 of file hba.c.

References HbaLine::addr, Assert, HbaLine::auth_method, buffer, clean_ipv6_addr(), HbaLine::conntype, CStringGetTextDatum, ctHost, ctHostNoSSL, ctHostSSL, ctLocal, HbaLine::databases, gethba_options(), heap_form_tuple(), HbaLine::hostname, Int32GetDatum, HbaLine::ip_cmp_method, ipCmpAll, ipCmpMask, ipCmpSameHost, ipCmpSameNet, lappend(), lengthof, lfirst, HbaLine::mask, tupleDesc::natts, NI_MAXHOST, NI_NUMERICHOST, NIL, NUM_PG_HBA_FILE_RULES_ATTS, options, pg_getnameinfo_all(), PointerGetDatum, pstrdup(), HbaLine::roles, StaticAssertStmt, HbaToken::string, strlist_to_textarray(), tuplestore_puttuple(), USER_AUTH_LAST, UserAuthName, and values.

Referenced by fill_hba_view().

2340 {
2342  bool nulls[NUM_PG_HBA_FILE_RULES_ATTS];
2343  char buffer[NI_MAXHOST];
2344  HeapTuple tuple;
2345  int index;
2346  ListCell *lc;
2347  const char *typestr;
2348  const char *addrstr;
2349  const char *maskstr;
2350  ArrayType *options;
2351 
2353 
2354  memset(values, 0, sizeof(values));
2355  memset(nulls, 0, sizeof(nulls));
2356  index = 0;
2357 
2358  /* line_number */
2359  values[index++] = Int32GetDatum(lineno);
2360 
2361  if (hba != NULL)
2362  {
2363  /* type */
2364  /* Avoid a default: case so compiler will warn about missing cases */
2365  typestr = NULL;
2366  switch (hba->conntype)
2367  {
2368  case ctLocal:
2369  typestr = "local";
2370  break;
2371  case ctHost:
2372  typestr = "host";
2373  break;
2374  case ctHostSSL:
2375  typestr = "hostssl";
2376  break;
2377  case ctHostNoSSL:
2378  typestr = "hostnossl";
2379  break;
2380  }
2381  if (typestr)
2382  values[index++] = CStringGetTextDatum(typestr);
2383  else
2384  nulls[index++] = true;
2385 
2386  /* database */
2387  if (hba->databases)
2388  {
2389  /*
2390  * Flatten HbaToken list to string list. It might seem that we
2391  * should re-quote any quoted tokens, but that has been rejected
2392  * on the grounds that it makes it harder to compare the array
2393  * elements to other system catalogs. That makes entries like
2394  * "all" or "samerole" formally ambiguous ... but users who name
2395  * databases/roles that way are inflicting their own pain.
2396  */
2397  List *names = NIL;
2398 
2399  foreach(lc, hba->databases)
2400  {
2401  HbaToken *tok = lfirst(lc);
2402 
2403  names = lappend(names, tok->string);
2404  }
2405  values[index++] = PointerGetDatum(strlist_to_textarray(names));
2406  }
2407  else
2408  nulls[index++] = true;
2409 
2410  /* user */
2411  if (hba->roles)
2412  {
2413  /* Flatten HbaToken list to string list; see comment above */
2414  List *roles = NIL;
2415 
2416  foreach(lc, hba->roles)
2417  {
2418  HbaToken *tok = lfirst(lc);
2419 
2420  roles = lappend(roles, tok->string);
2421  }
2422  values[index++] = PointerGetDatum(strlist_to_textarray(roles));
2423  }
2424  else
2425  nulls[index++] = true;
2426 
2427  /* address and netmask */
2428  /* Avoid a default: case so compiler will warn about missing cases */
2429  addrstr = maskstr = NULL;
2430  switch (hba->ip_cmp_method)
2431  {
2432  case ipCmpMask:
2433  if (hba->hostname)
2434  {
2435  addrstr = hba->hostname;
2436  }
2437  else
2438  {
2439  if (pg_getnameinfo_all(&hba->addr, sizeof(hba->addr),
2440  buffer, sizeof(buffer),
2441  NULL, 0,
2442  NI_NUMERICHOST) == 0)
2443  {
2444  clean_ipv6_addr(hba->addr.ss_family, buffer);
2445  addrstr = pstrdup(buffer);
2446  }
2447  if (pg_getnameinfo_all(&hba->mask, sizeof(hba->mask),
2448  buffer, sizeof(buffer),
2449  NULL, 0,
2450  NI_NUMERICHOST) == 0)
2451  {
2452  clean_ipv6_addr(hba->mask.ss_family, buffer);
2453  maskstr = pstrdup(buffer);
2454  }
2455  }
2456  break;
2457  case ipCmpAll:
2458  addrstr = "all";
2459  break;
2460  case ipCmpSameHost:
2461  addrstr = "samehost";
2462  break;
2463  case ipCmpSameNet:
2464  addrstr = "samenet";
2465  break;
2466  }
2467  if (addrstr)
2468  values[index++] = CStringGetTextDatum(addrstr);
2469  else
2470  nulls[index++] = true;
2471  if (maskstr)
2472  values[index++] = CStringGetTextDatum(maskstr);
2473  else
2474  nulls[index++] = true;
2475 
2476  /*
2477  * Make sure UserAuthName[] tracks additions to the UserAuth enum
2478  */
2480  "UserAuthName[] must match the UserAuth enum");
2481 
2482  /* auth_method */
2483  values[index++] = CStringGetTextDatum(UserAuthName[hba->auth_method]);
2484 
2485  /* options */
2486  options = gethba_options(hba);
2487  if (options)
2488  values[index++] = PointerGetDatum(options);
2489  else
2490  nulls[index++] = true;
2491  }
2492  else
2493  {
2494  /* no parsing result, so set relevant fields to nulls */
2495  memset(&nulls[1], true, (NUM_PG_HBA_FILE_RULES_ATTS - 2) * sizeof(bool));
2496  }
2497 
2498  /* error */
2499  if (err_msg)
2500  values[NUM_PG_HBA_FILE_RULES_ATTS - 1] = CStringGetTextDatum(err_msg);
2501  else
2502  nulls[NUM_PG_HBA_FILE_RULES_ATTS - 1] = true;
2503 
2504  tuple = heap_form_tuple(tupdesc, values, nulls);
2505  tuplestore_puttuple(tuple_store, tuple);
2506 }
List * databases
Definition: hba.h:66
#define NIL
Definition: pg_list.h:69
struct sockaddr_storage mask
Definition: hba.h:69
#define NI_NUMERICHOST
Definition: getaddrinfo.h:78
#define PointerGetDatum(X)
Definition: postgres.h:562
Definition: hba.h:47
char * pstrdup(const char *in)
Definition: mcxt.c:1076
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:695
static const char *const UserAuthName[]
Definition: hba.c:121
#define lengthof(array)
Definition: c.h:556
int natts
Definition: tupdesc.h:73
Definition: type.h:89
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:746
ConnType conntype
Definition: hba.h:65
Definition: hba.h:57
#define NI_MAXHOST
Definition: getaddrinfo.h:88
struct sockaddr_storage addr
Definition: hba.h:68
void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
Definition: tuplestore.c:730
Definition: hba.c:75
#define USER_AUTH_LAST
Definition: hba.h:42
Definition: hba.h:55
List * lappend(List *list, void *datum)
Definition: list.c:128
static char ** options
Definition: hba.h:50
uintptr_t Datum
Definition: postgres.h:372
char * hostname
Definition: hba.h:71
char * string
Definition: hba.c:77
List * roles
Definition: hba.h:67
#define Assert(condition)
Definition: c.h:664
#define lfirst(lc)
Definition: pg_list.h:106
int pg_getnameinfo_all(const struct sockaddr_storage *addr, int salen, char *node, int nodelen, char *service, int servicelen, int flags)
Definition: ip.c:122
#define NUM_PG_HBA_FILE_RULES_ATTS
Definition: hba.c:2323
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:214
void clean_ipv6_addr(int addr_family, char *addr)
Definition: network.c:1514
static Datum values[MAXATTR]
Definition: bootstrap.c:164
#define Int32GetDatum(X)
Definition: postgres.h:485
#define CStringGetTextDatum(s)
Definition: builtins.h:91
ArrayType * strlist_to_textarray(List *list)
IPCompareMethod ip_cmp_method
Definition: hba.h:70
Definition: pg_list.h:45
Definition: hba.h:56
UserAuth auth_method
Definition: hba.h:72
static ArrayType * gethba_options(HbaLine *hba)
Definition: hba.c:2215
static void fill_hba_view ( Tuplestorestate tuple_store,
TupleDesc  tupdesc 
)
static

Definition at line 2512 of file hba.c.

References AllocateFile(), ALLOCSET_SMALL_SIZES, AllocSetContextCreate(), CurrentMemoryContext, DEBUG3, ereport, TokenizedLine::err_msg, errcode_for_file_access(), errmsg(), ERROR, fill_hba_line(), FreeFile(), HbaFileName, lfirst, TokenizedLine::line_num, MemoryContextDelete(), MemoryContextSwitchTo(), NIL, parse_hba_line(), and tokenize_file().

Referenced by pg_hba_file_rules().

2513 {
2514  FILE *file;
2515  List *hba_lines = NIL;
2516  ListCell *line;
2517  MemoryContext linecxt;
2518  MemoryContext hbacxt;
2519  MemoryContext oldcxt;
2520 
2521  /*
2522  * In the unlikely event that we can't open pg_hba.conf, we throw an
2523  * error, rather than trying to report it via some sort of view entry.
2524  * (Most other error conditions should result in a message in a view
2525  * entry.)
2526  */
2527  file = AllocateFile(HbaFileName, "r");
2528  if (file == NULL)
2529  ereport(ERROR,
2531  errmsg("could not open configuration file \"%s\": %m",
2532  HbaFileName)));
2533 
2534  linecxt = tokenize_file(HbaFileName, file, &hba_lines, DEBUG3);
2535  FreeFile(file);
2536 
2537  /* Now parse all the lines */
2539  "hba parser context",
2541  oldcxt = MemoryContextSwitchTo(hbacxt);
2542  foreach(line, hba_lines)
2543  {
2544  TokenizedLine *tok_line = (TokenizedLine *) lfirst(line);
2545  HbaLine *hbaline = NULL;
2546 
2547  /* don't parse lines that already have errors */
2548  if (tok_line->err_msg == NULL)
2549  hbaline = parse_hba_line(tok_line, DEBUG3);
2550 
2551  fill_hba_line(tuple_store, tupdesc, tok_line->line_num,
2552  hbaline, tok_line->err_msg);
2553  }
2554 
2555  /* Free tokenizer memory */
2556  MemoryContextDelete(linecxt);
2557  /* Free parse_hba_line memory */
2558  MemoryContextSwitchTo(oldcxt);
2559  MemoryContextDelete(hbacxt);
2560 }
Definition: hba.h:61
#define NIL
Definition: pg_list.h:69
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
#define DEBUG3
Definition: elog.h:23
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:175
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
char * HbaFileName
Definition: guc.c:463
#define ERROR
Definition: elog.h:43
int line_num
Definition: hba.c:92
char * err_msg
Definition: hba.c:94
int errcode_for_file_access(void)
Definition: elog.c:598
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2117
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
#define ereport(elevel, rest)
Definition: elog.h:122
static HbaLine * parse_hba_line(TokenizedLine *tok_line, int elevel)
Definition: hba.c:945
static void fill_hba_line(Tuplestorestate *tuple_store, TupleDesc tupdesc, int lineno, HbaLine *hba, const char *err_msg)
Definition: hba.c:2338
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
#define lfirst(lc)
Definition: pg_list.h:106
static MemoryContext tokenize_file(const char *filename, FILE *file, List **tok_lines, int elevel)
Definition: hba.c:470
int FreeFile(FILE *file)
Definition: fd.c:2309
int errmsg(const char *fmt,...)
Definition: elog.c:797
Definition: pg_list.h:45
static ArrayType * gethba_options ( HbaLine hba)
static

Definition at line 2215 of file hba.c.

References Assert, HbaLine::auth_method, HbaLine::clientcert, construct_array(), CStringGetTextDatum, HbaLine::include_realm, HbaLine::krb_realm, HbaLine::ldapbasedn, HbaLine::ldapbinddn, HbaLine::ldapbindpasswd, HbaLine::ldapport, HbaLine::ldapprefix, HbaLine::ldapscope, HbaLine::ldapsearchattribute, HbaLine::ldapsearchfilter, HbaLine::ldapserver, HbaLine::ldapsuffix, HbaLine::ldaptls, MAX_HBA_OPTIONS, noptions, HbaLine::pamservice, psprintf(), HbaLine::radiusidentifiers_s, HbaLine::radiusports_s, HbaLine::radiussecrets_s, HbaLine::radiusservers_s, TEXTOID, uaGSS, uaLDAP, uaRADIUS, uaSSPI, and HbaLine::usermap.

Referenced by fill_hba_line().

2216 {
2217  int noptions;
2219 
2220  noptions = 0;
2221 
2222  if (hba->auth_method == uaGSS || hba->auth_method == uaSSPI)
2223  {
2224  if (hba->include_realm)
2225  options[noptions++] =
2226  CStringGetTextDatum("include_realm=true");
2227 
2228  if (hba->krb_realm)
2229  options[noptions++] =
2230  CStringGetTextDatum(psprintf("krb_realm=%s", hba->krb_realm));
2231  }
2232 
2233  if (hba->usermap)
2234  options[noptions++] =
2235  CStringGetTextDatum(psprintf("map=%s", hba->usermap));
2236 
2237  if (hba->clientcert)
2238  options[noptions++] =
2239  CStringGetTextDatum("clientcert=true");
2240 
2241  if (hba->pamservice)
2242  options[noptions++] =
2243  CStringGetTextDatum(psprintf("pamservice=%s", hba->pamservice));
2244 
2245  if (hba->auth_method == uaLDAP)
2246  {
2247  if (hba->ldapserver)
2248  options[noptions++] =
2249  CStringGetTextDatum(psprintf("ldapserver=%s", hba->ldapserver));
2250 
2251  if (hba->ldapport)
2252  options[noptions++] =
2253  CStringGetTextDatum(psprintf("ldapport=%d", hba->ldapport));
2254 
2255  if (hba->ldaptls)
2256  options[noptions++] =
2257  CStringGetTextDatum("ldaptls=true");
2258 
2259  if (hba->ldapprefix)
2260  options[noptions++] =
2261  CStringGetTextDatum(psprintf("ldapprefix=%s", hba->ldapprefix));
2262 
2263  if (hba->ldapsuffix)
2264  options[noptions++] =
2265  CStringGetTextDatum(psprintf("ldapsuffix=%s", hba->ldapsuffix));
2266 
2267  if (hba->ldapbasedn)
2268  options[noptions++] =
2269  CStringGetTextDatum(psprintf("ldapbasedn=%s", hba->ldapbasedn));
2270 
2271  if (hba->ldapbinddn)
2272  options[noptions++] =
2273  CStringGetTextDatum(psprintf("ldapbinddn=%s", hba->ldapbinddn));
2274 
2275  if (hba->ldapbindpasswd)
2276  options[noptions++] =
2277  CStringGetTextDatum(psprintf("ldapbindpasswd=%s",
2278  hba->ldapbindpasswd));
2279 
2280  if (hba->ldapsearchattribute)
2281  options[noptions++] =
2282  CStringGetTextDatum(psprintf("ldapsearchattribute=%s",
2283  hba->ldapsearchattribute));
2284 
2285  if (hba->ldapsearchfilter)
2286  options[noptions++] =
2287  CStringGetTextDatum(psprintf("ldapsearchfilter=%s",
2288  hba->ldapsearchfilter));
2289 
2290  if (hba->ldapscope)
2291  options[noptions++] =
2292  CStringGetTextDatum(psprintf("ldapscope=%d", hba->ldapscope));
2293  }
2294 
2295  if (hba->auth_method == uaRADIUS)
2296  {
2297  if (hba->radiusservers_s)
2298  options[noptions++] =
2299  CStringGetTextDatum(psprintf("radiusservers=%s", hba->radiusservers_s));
2300 
2301  if (hba->radiussecrets_s)
2302  options[noptions++] =
2303  CStringGetTextDatum(psprintf("radiussecrets=%s", hba->radiussecrets_s));
2304 
2305  if (hba->radiusidentifiers_s)
2306  options[noptions++] =
2307  CStringGetTextDatum(psprintf("radiusidentifiers=%s", hba->radiusidentifiers_s));
2308 
2309  if (hba->radiusports_s)
2310  options[noptions++] =
2311  CStringGetTextDatum(psprintf("radiusports=%s", hba->radiusports_s));
2312  }
2313 
2314  Assert(noptions <= MAX_HBA_OPTIONS);
2315 
2316  if (noptions > 0)
2317  return construct_array(options, noptions, TEXTOID, -1, false, 'i');
2318  else
2319  return NULL;
2320 }
int ldapscope
Definition: hba.h:85
char * radiusports_s
Definition: hba.h:100
char * ldapserver
Definition: hba.h:78
Definition: hba.h:38
int ldapport
Definition: hba.h:79
char * ldapbasedn
Definition: hba.h:84
char * pamservice
Definition: hba.h:75
#define TEXTOID
Definition: pg_type.h:324
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
Definition: hba.h:35
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3307
char * ldapsuffix
Definition: hba.h:87
Definition: hba.h:34
char * radiusservers_s
Definition: hba.h:94
char * usermap
Definition: hba.h:74
bool include_realm
Definition: hba.h:90
char * ldapbinddn
Definition: hba.h:80
char * krb_realm
Definition: hba.h:89
char * ldapbindpasswd
Definition: hba.h:81
char * ldapprefix
Definition: hba.h:86
uintptr_t Datum
Definition: postgres.h:372
char * radiusidentifiers_s
Definition: hba.h:98
char * radiussecrets_s
Definition: hba.h:96
#define Assert(condition)
Definition: c.h:664
char * ldapsearchfilter
Definition: hba.h:83
bool ldaptls
Definition: hba.h:77
char * ldapsearchattribute
Definition: hba.h:82
#define CStringGetTextDatum(s)
Definition: builtins.h:91
bool clientcert
Definition: hba.h:88
static size_t noptions
Definition: hba.h:40
UserAuth auth_method
Definition: hba.h:72
#define MAX_HBA_OPTIONS
Definition: hba.c:2208
void hba_getauthmethod ( hbaPort port)

Definition at line 3008 of file hba.c.

References check_hba().

Referenced by ClientAuthentication().

3009 {
3010  check_hba(port);
3011 }
static void check_hba(hbaPort *port)
Definition: hba.c:2009
static bool hostname_match ( const char *  pattern,
const char *  actual_hostname 
)
static

Definition at line 673 of file hba.c.

References pg_strcasecmp().

Referenced by check_hostname().

674 {
675  if (pattern[0] == '.') /* suffix match */
676  {
677  size_t plen = strlen(pattern);
678  size_t hlen = strlen(actual_hostname);
679 
680  if (hlen < plen)
681  return false;
682 
683  return (pg_strcasecmp(pattern, actual_hostname + (hlen - plen)) == 0);
684  }
685  else
686  return (pg_strcasecmp(pattern, actual_hostname) == 0);
687 }
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
static bool ipv4eq ( struct sockaddr_in *  a,
struct sockaddr_in *  b 
)
static

Definition at line 649 of file hba.c.

Referenced by check_hostname().

650 {
651  return (a->sin_addr.s_addr == b->sin_addr.s_addr);
652 }
static bool is_member ( Oid  userid,
const char *  role 
)
static

Definition at line 562 of file hba.c.

References get_role_oid(), is_member_of_role_nosuper(), and OidIsValid.

Referenced by check_db(), and check_role().

563 {
564  Oid roleid;
565 
566  if (!OidIsValid(userid))
567  return false; /* if user not exist, say "no" */
568 
569  roleid = get_role_oid(role, true);
570 
571  if (!OidIsValid(roleid))
572  return false; /* if target role not exist, say "no" */
573 
574  /*
575  * See if user is directly or indirectly a member of role. For this
576  * purpose, a superuser is not considered to be automatically a member of
577  * the role, so group auth only applies to explicit membership.
578  */
579  return is_member_of_role_nosuper(userid, roleid);
580 }
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:532
Oid get_role_oid(const char *rolname, bool missing_ok)
Definition: acl.c:5111
bool is_member_of_role_nosuper(Oid member, Oid role)
Definition: acl.c:4890
bool load_hba ( void  )

Definition at line 2110 of file hba.c.

References AllocateFile(), ALLOCSET_SMALL_SIZES, AllocSetContextCreate(), Assert, ereport, TokenizedLine::err_msg, errcode(), errcode_for_file_access(), errmsg(), FreeFile(), HbaFileName, lappend(), lfirst, LOG, MemoryContextDelete(), MemoryContextSwitchTo(), newline(), NIL, parse_hba_line(), PostmasterContext, and tokenize_file().

Referenced by PerformAuthentication(), PostmasterMain(), and SIGHUP_handler().

2111 {
2112  FILE *file;
2113  List *hba_lines = NIL;
2114  ListCell *line;
2115  List *new_parsed_lines = NIL;
2116  bool ok = true;
2117  MemoryContext linecxt;
2118  MemoryContext oldcxt;
2119  MemoryContext hbacxt;
2120 
2121  file = AllocateFile(HbaFileName, "r");
2122  if (file == NULL)
2123  {
2124  ereport(LOG,
2126  errmsg("could not open configuration file \"%s\": %m",
2127  HbaFileName)));
2128  return false;
2129  }
2130 
2131  linecxt = tokenize_file(HbaFileName, file, &hba_lines, LOG);
2132  FreeFile(file);
2133 
2134  /* Now parse all the lines */
2137  "hba parser context",
2139  oldcxt = MemoryContextSwitchTo(hbacxt);
2140  foreach(line, hba_lines)
2141  {
2142  TokenizedLine *tok_line = (TokenizedLine *) lfirst(line);
2143  HbaLine *newline;
2144 
2145  /* don't parse lines that already have errors */
2146  if (tok_line->err_msg != NULL)
2147  {
2148  ok = false;
2149  continue;
2150  }
2151 
2152  if ((newline = parse_hba_line(tok_line, LOG)) == NULL)
2153  {
2154  /* Parse error; remember there's trouble */
2155  ok = false;
2156 
2157  /*
2158  * Keep parsing the rest of the file so we can report errors on
2159  * more than the first line. Error has already been logged, no
2160  * need for more chatter here.
2161  */
2162  continue;
2163  }
2164 
2165  new_parsed_lines = lappend(new_parsed_lines, newline);
2166  }
2167 
2168  /*
2169  * A valid HBA file must have at least one entry; else there's no way to
2170  * connect to the postmaster. But only complain about this if we didn't
2171  * already have parsing errors.
2172  */
2173  if (ok && new_parsed_lines == NIL)
2174  {
2175  ereport(LOG,
2176  (errcode(ERRCODE_CONFIG_FILE_ERROR),
2177  errmsg("configuration file \"%s\" contains no entries",
2178  HbaFileName)));
2179  ok = false;
2180  }
2181 
2182  /* Free tokenizer memory */
2183  MemoryContextDelete(linecxt);
2184  MemoryContextSwitchTo(oldcxt);
2185 
2186  if (!ok)
2187  {
2188  /* File contained one or more errors, so bail out */
2189  MemoryContextDelete(hbacxt);
2190  return false;
2191  }
2192 
2193  /* Loaded new file successfully, replace the one we use */
2194  if (parsed_hba_context != NULL)
2196  parsed_hba_context = hbacxt;
2197  parsed_hba_lines = new_parsed_lines;
2198 
2199  return true;
2200 }
Definition: hba.h:61
#define NIL
Definition: pg_list.h:69
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:175
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:575
#define LOG
Definition: elog.h:26
static chr newline(void)
Definition: regc_lex.c:1137
static List * parsed_hba_lines
Definition: hba.c:101
char * HbaFileName
Definition: guc.c:463
static MemoryContext parsed_hba_context
Definition: hba.c:102
char * err_msg
Definition: hba.c:94
int errcode_for_file_access(void)
Definition: elog.c:598
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2117
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
static HbaLine * parse_hba_line(TokenizedLine *tok_line, int elevel)
Definition: hba.c:945
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
#define Assert(condition)
Definition: c.h:664
#define lfirst(lc)
Definition: pg_list.h:106
static MemoryContext tokenize_file(const char *filename, FILE *file, List **tok_lines, int elevel)
Definition: hba.c:470
int FreeFile(FILE *file)
Definition: fd.c:2309
int errmsg(const char *fmt,...)
Definition: elog.c:797
Definition: pg_list.h:45
MemoryContext PostmasterContext
Definition: mcxt.c:45
bool load_ident ( void  )

Definition at line 2897 of file hba.c.

References AllocateFile(), ALLOCSET_SMALL_SIZES, AllocSetContextCreate(), Assert, ereport, TokenizedLine::err_msg, errcode_for_file_access(), errmsg(), FreeFile(), IdentLine::ident_user, IdentFileName, lappend(), lfirst, LOG, MemoryContextDelete(), MemoryContextSwitchTo(), newline(), NIL, parse_ident_line(), pg_regfree(), PostmasterContext, IdentLine::re, and tokenize_file().

Referenced by PerformAuthentication(), PostmasterMain(), and SIGHUP_handler().

2898 {
2899  FILE *file;
2900  List *ident_lines = NIL;
2901  ListCell *line_cell,
2902  *parsed_line_cell;
2903  List *new_parsed_lines = NIL;
2904  bool ok = true;
2905  MemoryContext linecxt;
2906  MemoryContext oldcxt;
2907  MemoryContext ident_context;
2908  IdentLine *newline;
2909 
2910  file = AllocateFile(IdentFileName, "r");
2911  if (file == NULL)
2912  {
2913  /* not fatal ... we just won't do any special ident maps */
2914  ereport(LOG,
2916  errmsg("could not open usermap file \"%s\": %m",
2917  IdentFileName)));
2918  return false;
2919  }
2920 
2921  linecxt = tokenize_file(IdentFileName, file, &ident_lines, LOG);
2922  FreeFile(file);
2923 
2924  /* Now parse all the lines */
2926  ident_context = AllocSetContextCreate(PostmasterContext,
2927  "ident parser context",
2929  oldcxt = MemoryContextSwitchTo(ident_context);
2930  foreach(line_cell, ident_lines)
2931  {
2932  TokenizedLine *tok_line = (TokenizedLine *) lfirst(line_cell);
2933 
2934  /* don't parse lines that already have errors */
2935  if (tok_line->err_msg != NULL)
2936  {
2937  ok = false;
2938  continue;
2939  }
2940 
2941  if ((newline = parse_ident_line(tok_line)) == NULL)
2942  {
2943  /* Parse error; remember there's trouble */
2944  ok = false;
2945 
2946  /*
2947  * Keep parsing the rest of the file so we can report errors on
2948  * more than the first line. Error has already been logged, no
2949  * need for more chatter here.
2950  */
2951  continue;
2952  }
2953 
2954  new_parsed_lines = lappend(new_parsed_lines, newline);
2955  }
2956 
2957  /* Free tokenizer memory */
2958  MemoryContextDelete(linecxt);
2959  MemoryContextSwitchTo(oldcxt);
2960 
2961  if (!ok)
2962  {
2963  /*
2964  * File contained one or more errors, so bail out, first being careful
2965  * to clean up whatever we allocated. Most stuff will go away via
2966  * MemoryContextDelete, but we have to clean up regexes explicitly.
2967  */
2968  foreach(parsed_line_cell, new_parsed_lines)
2969  {
2970  newline = (IdentLine *) lfirst(parsed_line_cell);
2971  if (newline->ident_user[0] == '/')
2972  pg_regfree(&newline->re);
2973  }
2974  MemoryContextDelete(ident_context);
2975  return false;
2976  }
2977 
2978  /* Loaded new file successfully, replace the one we use */
2979  if (parsed_ident_lines != NIL)
2980  {
2981  foreach(parsed_line_cell, parsed_ident_lines)
2982  {
2983  newline = (IdentLine *) lfirst(parsed_line_cell);
2984  if (newline->ident_user[0] == '/')
2985  pg_regfree(&newline->re);
2986  }
2987  }
2988  if (parsed_ident_context != NULL)
2990 
2991  parsed_ident_context = ident_context;
2992  parsed_ident_lines = new_parsed_lines;
2993 
2994  return true;
2995 }
#define NIL
Definition: pg_list.h:69
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
regex_t re
Definition: hba.h:110
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:175
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define LOG
Definition: elog.h:26
static chr newline(void)
Definition: regc_lex.c:1137
char * err_msg
Definition: hba.c:94
int errcode_for_file_access(void)
Definition: elog.c:598
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2117
char * IdentFileName
Definition: guc.c:464
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
static List * parsed_ident_lines
Definition: hba.c:112
static MemoryContext parsed_ident_context
Definition: hba.c:113
#define Assert(condition)
Definition: c.h:664
#define lfirst(lc)
Definition: pg_list.h:106
static MemoryContext tokenize_file(const char *filename, FILE *file, List **tok_lines, int elevel)
Definition: hba.c:470
Definition: hba.h:103
int FreeFile(FILE *file)
Definition: fd.c:2309
char * ident_user
Definition: hba.h:108
int errmsg(const char *fmt,...)
Definition: elog.c:797
static IdentLine * parse_ident_line(TokenizedLine *tok_line)
Definition: hba.c:2629
void pg_regfree(regex_t *re)
Definition: regfree.c:49
Definition: pg_list.h:45
MemoryContext PostmasterContext
Definition: mcxt.c:45
static HbaToken* make_hba_token ( const char *  token,
bool  quoted 
)
static

Definition at line 288 of file hba.c.

References palloc(), HbaToken::quoted, and HbaToken::string.

Referenced by copy_hba_token(), and next_field_expand().

289 {
290  HbaToken *hbatoken;
291  int toklen;
292 
293  toklen = strlen(token);
294  /* we copy string into same palloc block as the struct */
295  hbatoken = (HbaToken *) palloc(sizeof(HbaToken) + toklen + 1);
296  hbatoken->string = (char *) hbatoken + sizeof(HbaToken);
297  hbatoken->quoted = quoted;
298  memcpy(hbatoken->string, token, toklen + 1);
299 
300  return hbatoken;
301 }
Definition: hba.c:75
char * string
Definition: hba.c:77
bool quoted
Definition: hba.c:78
void * palloc(Size size)
Definition: mcxt.c:848
static List* next_field_expand ( const char *  filename,
char **  lineptr,
int  elevel,
char **  err_msg 
)
static

Definition at line 330 of file hba.c.

References buf, lappend(), make_hba_token(), MAX_TOKEN, next_token(), NIL, and tokenize_inc_file().

Referenced by tokenize_file().

332 {
333  char buf[MAX_TOKEN];
334  bool trailing_comma;
335  bool initial_quote;
336  List *tokens = NIL;
337 
338  do
339  {
340  if (!next_token(lineptr, buf, sizeof(buf),
341  &initial_quote, &trailing_comma,
342  elevel, err_msg))
343  break;
344 
345  /* Is this referencing a file? */
346  if (!initial_quote && buf[0] == '@' && buf[1] != '\0')
347  tokens = tokenize_inc_file(tokens, filename, buf + 1,
348  elevel, err_msg);
349  else
350  tokens = lappend(tokens, make_hba_token(buf, initial_quote));
351  } while (trailing_comma && (*err_msg == NULL));
352 
353  return tokens;
354 }
#define NIL
Definition: pg_list.h:69
static bool next_token(char **lineptr, char *buf, int bufsz, bool *initial_quote, bool *terminating_comma, int elevel, char **err_msg)
Definition: hba.c:195
static char * buf
Definition: pg_test_fsync.c:67
List * lappend(List *list, void *datum)
Definition: list.c:128
static int elevel
Definition: vacuumlazy.c:136
#define MAX_TOKEN
Definition: hba.c:56
static char * filename
Definition: pg_dumpall.c:90
Definition: pg_list.h:45
static List * tokenize_inc_file(List *tokens, const char *outer_filename, const char *inc_filename, int elevel, char **err_msg)
Definition: hba.c:372
static HbaToken * make_hba_token(const char *token, bool quoted)
Definition: hba.c:288
static bool next_token ( char **  lineptr,
char *  buf,
int  bufsz,
bool initial_quote,
bool terminating_comma,
int  elevel,
char **  err_msg 
)
static

Definition at line 195 of file hba.c.

References Assert, buf, ereport, errcode(), errmsg(), and pg_isblank().

Referenced by base_yylex(), filtered_base_yylex(), and next_field_expand().

198 {
199  int c;
200  char *start_buf = buf;
201  char *end_buf = buf + (bufsz - 1);
202  bool in_quote = false;
203  bool was_quote = false;
204  bool saw_quote = false;
205 
206  Assert(end_buf > start_buf);
207 
208  *initial_quote = false;
209  *terminating_comma = false;
210 
211  /* Move over any whitespace and commas preceding the next token */
212  while ((c = (*(*lineptr)++)) != '\0' && (pg_isblank(c) || c == ','))
213  ;
214 
215  /*
216  * Build a token in buf of next characters up to EOL, unquoted comma, or
217  * unquoted whitespace.
218  */
219  while (c != '\0' &&
220  (!pg_isblank(c) || in_quote))
221  {
222  /* skip comments to EOL */
223  if (c == '#' && !in_quote)
224  {
225  while ((c = (*(*lineptr)++)) != '\0')
226  ;
227  break;
228  }
229 
230  if (buf >= end_buf)
231  {
232  *buf = '\0';
233  ereport(elevel,
234  (errcode(ERRCODE_CONFIG_FILE_ERROR),
235  errmsg("authentication file token too long, skipping: \"%s\"",
236  start_buf)));
237  *err_msg = "authentication file token too long";
238  /* Discard remainder of line */
239  while ((c = (*(*lineptr)++)) != '\0')
240  ;
241  /* Un-eat the '\0', in case we're called again */
242  (*lineptr)--;
243  return false;
244  }
245 
246  /* we do not pass back a terminating comma in the token */
247  if (c == ',' && !in_quote)
248  {
249  *terminating_comma = true;
250  break;
251  }
252 
253  if (c != '"' || was_quote)
254  *buf++ = c;
255 
256  /* Literal double-quote is two double-quotes */
257  if (in_quote && c == '"')
258  was_quote = !was_quote;
259  else
260  was_quote = false;
261 
262  if (c == '"')
263  {
264  in_quote = !in_quote;
265  saw_quote = true;
266  if (buf == start_buf)
267  *initial_quote = true;
268  }
269 
270  c = *(*lineptr)++;
271  }
272 
273  /*
274  * Un-eat the char right after the token (critical in case it is '\0',
275  * else next call will read past end of string).
276  */
277  (*lineptr)--;
278 
279  *buf = '\0';
280 
281  return (saw_quote || buf > start_buf);
282 }
bool pg_isblank(const char c)
Definition: hba.c:160
int errcode(int sqlerrcode)
Definition: elog.c:575
char * c
static char * buf
Definition: pg_test_fsync.c:67
#define ereport(elevel, rest)
Definition: elog.h:122
static int elevel
Definition: vacuumlazy.c:136
#define Assert(condition)
Definition: c.h:664
int errmsg(const char *fmt,...)
Definition: elog.c:797
static bool parse_hba_auth_opt ( char *  name,
char *  val,
HbaLine hbaline,
int  elevel,
char **  err_msg 
)
static

Definition at line 1647 of file hba.c.

References addrinfo::ai_family, addrinfo::ai_socktype, HbaLine::auth_method, HbaLine::clientcert, HbaLine::compat_realm, HbaLine::conntype, ctHostSSL, ereport, errcode(), errcontext, errmsg(), gai_strerror, gettext_noop, HbaFileName, HbaLine::include_realm, INVALID_AUTH_OPTION, HbaLine::krb_realm, HbaLine::ldapbasedn, HbaLine::ldapbinddn, HbaLine::ldapbindpasswd, HbaLine::ldapport, HbaLine::ldapprefix, HbaLine::ldapscope, HbaLine::ldapsearchattribute, HbaLine::ldapsearchfilter, HbaLine::ldapserver, HbaLine::ldapsuffix, HbaLine::ldaptls, lfirst, HbaLine::linenumber, list_free(), MemSet, HbaLine::pam_use_hostname, HbaLine::pamservice, pg_freeaddrinfo_all(), pg_getaddrinfo_all(), psprintf(), pstrdup(), HbaLine::radiusidentifiers, HbaLine::radiusidentifiers_s, HbaLine::radiusports, HbaLine::radiusports_s, HbaLine::radiussecrets, HbaLine::radiussecrets_s, HbaLine::radiusservers, HbaLine::radiusservers_s, REQUIRE_AUTH_OPTION, SplitIdentifierString(), uaCert, uaGSS, uaIdent, uaLDAP, uaPAM, uaRADIUS, uaSSPI, HbaLine::upn_username, and HbaLine::usermap.

Referenced by parse_hba_line().

1649 {
1650  int line_num = hbaline->linenumber;
1651 
1652 #ifdef USE_LDAP
1653  hbaline->ldapscope = LDAP_SCOPE_SUBTREE;
1654 #endif
1655 
1656  if (strcmp(name, "map") == 0)
1657  {
1658  if (hbaline->auth_method != uaIdent &&
1659  hbaline->auth_method != uaPeer &&
1660  hbaline->auth_method != uaGSS &&
1661  hbaline->auth_method != uaSSPI &&
1662  hbaline->auth_method != uaCert)
1663  INVALID_AUTH_OPTION("map", gettext_noop("ident, peer, gssapi, sspi, and cert"));
1664  hbaline->usermap = pstrdup(val);
1665  }
1666  else if (strcmp(name, "clientcert") == 0)
1667  {
1668  if (hbaline->conntype != ctHostSSL)
1669  {
1670  ereport(elevel,
1671  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1672  errmsg("clientcert can only be configured for \"hostssl\" rows"),
1673  errcontext("line %d of configuration file \"%s\"",
1674  line_num, HbaFileName)));
1675  *err_msg = "clientcert can only be configured for \"hostssl\" rows";
1676  return false;
1677  }
1678  if (strcmp(val, "1") == 0)
1679  {
1680  hbaline->clientcert = true;
1681  }
1682  else
1683  {
1684  if (hbaline->auth_method == uaCert)
1685  {
1686  ereport(elevel,
1687  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1688  errmsg("clientcert can not be set to 0 when using \"cert\" authentication"),
1689  errcontext("line %d of configuration file \"%s\"",
1690  line_num, HbaFileName)));
1691  *err_msg = "clientcert can not be set to 0 when using \"cert\" authentication";
1692  return false;
1693  }
1694  hbaline->clientcert = false;
1695  }
1696  }
1697  else if (strcmp(name, "pamservice") == 0)
1698  {
1699  REQUIRE_AUTH_OPTION(uaPAM, "pamservice", "pam");
1700  hbaline->pamservice = pstrdup(val);
1701  }
1702  else if (strcmp(name, "pam_use_hostname") == 0)
1703  {
1704  REQUIRE_AUTH_OPTION(uaPAM, "pam_use_hostname", "pam");
1705  if (strcmp(val, "1") == 0)
1706  hbaline->pam_use_hostname = true;
1707  else
1708  hbaline->pam_use_hostname = false;
1709 
1710  }
1711  else if (strcmp(name, "ldapurl") == 0)
1712  {
1713 #ifdef LDAP_API_FEATURE_X_OPENLDAP
1714  LDAPURLDesc *urldata;
1715  int rc;
1716 #endif
1717 
1718  REQUIRE_AUTH_OPTION(uaLDAP, "ldapurl", "ldap");
1719 #ifdef LDAP_API_FEATURE_X_OPENLDAP
1720  rc = ldap_url_parse(val, &urldata);
1721  if (rc != LDAP_SUCCESS)
1722  {
1723  ereport(elevel,
1724  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1725  errmsg("could not parse LDAP URL \"%s\": %s", val, ldap_err2string(rc))));
1726  *err_msg = psprintf("could not parse LDAP URL \"%s\": %s",
1727  val, ldap_err2string(rc));
1728  return false;
1729  }
1730 
1731  if (strcmp(urldata->lud_scheme, "ldap") != 0)
1732  {
1733  ereport(elevel,
1734  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1735  errmsg("unsupported LDAP URL scheme: %s", urldata->lud_scheme)));
1736  *err_msg = psprintf("unsupported LDAP URL scheme: %s",
1737  urldata->lud_scheme);
1738  ldap_free_urldesc(urldata);
1739  return false;
1740  }
1741 
1742  hbaline->ldapserver = pstrdup(urldata->lud_host);
1743  hbaline->ldapport = urldata->lud_port;
1744  hbaline->ldapbasedn = pstrdup(urldata->lud_dn);
1745 
1746  if (urldata->lud_attrs)
1747  hbaline->ldapsearchattribute = pstrdup(urldata->lud_attrs[0]); /* only use first one */
1748  hbaline->ldapscope = urldata->lud_scope;
1749  if (urldata->lud_filter)
1750  hbaline->ldapsearchfilter = pstrdup(urldata->lud_filter);
1751  ldap_free_urldesc(urldata);
1752 #else /* not OpenLDAP */
1753  ereport(elevel,
1754  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1755  errmsg("LDAP URLs not supported on this platform")));
1756  *err_msg = "LDAP URLs not supported on this platform";
1757 #endif /* not OpenLDAP */
1758  }
1759  else if (strcmp(name, "ldaptls") == 0)
1760  {
1761  REQUIRE_AUTH_OPTION(uaLDAP, "ldaptls", "ldap");
1762  if (strcmp(val, "1") == 0)
1763  hbaline->ldaptls = true;
1764  else
1765  hbaline->ldaptls = false;
1766  }
1767  else if (strcmp(name, "ldapserver") == 0)
1768  {
1769  REQUIRE_AUTH_OPTION(uaLDAP, "ldapserver", "ldap");
1770  hbaline->ldapserver = pstrdup(val);
1771  }
1772  else if (strcmp(name, "ldapport") == 0)
1773  {
1774  REQUIRE_AUTH_OPTION(uaLDAP, "ldapport", "ldap");
1775  hbaline->ldapport = atoi(val);
1776  if (hbaline->ldapport == 0)
1777  {
1778  ereport(elevel,
1779  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1780  errmsg("invalid LDAP port number: \"%s\"", val),
1781  errcontext("line %d of configuration file \"%s\"",
1782  line_num, HbaFileName)));
1783  *err_msg = psprintf("invalid LDAP port number: \"%s\"", val);
1784  return false;
1785  }
1786  }
1787  else if (strcmp(name, "ldapbinddn") == 0)
1788  {
1789  REQUIRE_AUTH_OPTION(uaLDAP, "ldapbinddn", "ldap");
1790  hbaline->ldapbinddn = pstrdup(val);
1791  }
1792  else if (strcmp(name, "ldapbindpasswd") == 0)
1793  {
1794  REQUIRE_AUTH_OPTION(uaLDAP, "ldapbindpasswd", "ldap");
1795  hbaline->ldapbindpasswd = pstrdup(val);
1796  }
1797  else if (strcmp(name, "ldapsearchattribute") == 0)
1798  {
1799  REQUIRE_AUTH_OPTION(uaLDAP, "ldapsearchattribute", "ldap");
1800  hbaline->ldapsearchattribute = pstrdup(val);
1801  }
1802  else if (strcmp(name, "ldapsearchfilter") == 0)
1803  {
1804  REQUIRE_AUTH_OPTION(uaLDAP, "ldapsearchfilter", "ldap");
1805  hbaline->ldapsearchfilter = pstrdup(val);
1806  }
1807  else if (strcmp(name, "ldapbasedn") == 0)
1808  {
1809  REQUIRE_AUTH_OPTION(uaLDAP, "ldapbasedn", "ldap");
1810  hbaline->ldapbasedn = pstrdup(val);
1811  }
1812  else if (strcmp(name, "ldapprefix") == 0)
1813  {
1814  REQUIRE_AUTH_OPTION(uaLDAP, "ldapprefix", "ldap");
1815  hbaline->ldapprefix = pstrdup(val);
1816  }
1817  else if (strcmp(name, "ldapsuffix") == 0)
1818  {
1819  REQUIRE_AUTH_OPTION(uaLDAP, "ldapsuffix", "ldap");
1820  hbaline->ldapsuffix = pstrdup(val);
1821  }
1822  else if (strcmp(name, "krb_realm") == 0)
1823  {
1824  if (hbaline->auth_method != uaGSS &&
1825  hbaline->auth_method != uaSSPI)
1826  INVALID_AUTH_OPTION("krb_realm", gettext_noop("gssapi and sspi"));
1827  hbaline->krb_realm = pstrdup(val);
1828  }
1829  else if (strcmp(name, "include_realm") == 0)
1830  {
1831  if (hbaline->auth_method != uaGSS &&
1832  hbaline->auth_method != uaSSPI)
1833  INVALID_AUTH_OPTION("include_realm", gettext_noop("gssapi and sspi"));
1834  if (strcmp(val, "1") == 0)
1835  hbaline->include_realm = true;
1836  else
1837  hbaline->include_realm = false;
1838  }
1839  else if (strcmp(name, "compat_realm") == 0)
1840  {
1841  if (hbaline->auth_method != uaSSPI)
1842  INVALID_AUTH_OPTION("compat_realm", gettext_noop("sspi"));
1843  if (strcmp(val, "1") == 0)
1844  hbaline->compat_realm = true;
1845  else
1846  hbaline->compat_realm = false;
1847  }
1848  else if (strcmp(name, "upn_username") == 0)
1849  {
1850  if (hbaline->auth_method != uaSSPI)
1851  INVALID_AUTH_OPTION("upn_username", gettext_noop("sspi"));
1852  if (strcmp(val, "1") == 0)
1853  hbaline->upn_username = true;
1854  else
1855  hbaline->upn_username = false;
1856  }
1857  else if (strcmp(name, "radiusservers") == 0)
1858  {
1859  struct addrinfo *gai_result;
1860  struct addrinfo hints;
1861  int ret;
1862  List *parsed_servers;
1863  ListCell *l;
1864  char *dupval = pstrdup(val);
1865 
1866  REQUIRE_AUTH_OPTION(uaRADIUS, "radiusservers", "radius");
1867 
1868  if (!SplitIdentifierString(dupval, ',', &parsed_servers))
1869  {
1870  /* syntax error in list */
1871  ereport(elevel,
1872  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1873  errmsg("could not parse RADIUS server list \"%s\"",
1874  val),
1875  errcontext("line %d of configuration file \"%s\"",
1876  line_num, HbaFileName)));
1877  return false;
1878  }
1879 
1880  /* For each entry in the list, translate it */
1881  foreach(l, parsed_servers)
1882  {
1883  MemSet(&hints, 0, sizeof(hints));
1884  hints.ai_socktype = SOCK_DGRAM;
1885  hints.ai_family = AF_UNSPEC;
1886 
1887  ret = pg_getaddrinfo_all((char *) lfirst(l), NULL, &hints, &gai_result);
1888  if (ret || !gai_result)
1889  {
1890  ereport(elevel,
1891  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1892  errmsg("could not translate RADIUS server name \"%s\" to address: %s",
1893  (char *) lfirst(l), gai_strerror(ret)),
1894  errcontext("line %d of configuration file \"%s\"",
1895  line_num, HbaFileName)));
1896  if (gai_result)
1897  pg_freeaddrinfo_all(hints.ai_family, gai_result);
1898 
1899  list_free(parsed_servers);
1900  return false;
1901  }
1902  pg_freeaddrinfo_all(hints.ai_family, gai_result);
1903  }
1904 
1905  /* All entries are OK, so store them */
1906  hbaline->radiusservers = parsed_servers;
1907  hbaline->radiusservers_s = pstrdup(val);
1908  }
1909  else if (strcmp(name, "radiusports") == 0)
1910  {
1911  List *parsed_ports;
1912  ListCell *l;
1913  char *dupval = pstrdup(val);
1914 
1915  REQUIRE_AUTH_OPTION(uaRADIUS, "radiusports", "radius");
1916 
1917  if (!SplitIdentifierString(dupval, ',', &parsed_ports))
1918  {
1919  ereport(elevel,
1920  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1921  errmsg("could not parse RADIUS port list \"%s\"",
1922  val),
1923  errcontext("line %d of configuration file \"%s\"",
1924  line_num, HbaFileName)));
1925  *err_msg = psprintf("invalid RADIUS port number: \"%s\"", val);
1926  return false;
1927  }
1928 
1929  foreach(l, parsed_ports)
1930  {
1931  if (atoi(lfirst(l)) == 0)
1932  {
1933  ereport(elevel,
1934  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1935  errmsg("invalid RADIUS port number: \"%s\"", val),
1936  errcontext("line %d of configuration file \"%s\"",
1937  line_num, HbaFileName)));
1938 
1939  return false;
1940  }
1941  }
1942  hbaline->radiusports = parsed_ports;
1943  hbaline->radiusports_s = pstrdup(val);
1944  }
1945  else if (strcmp(name, "radiussecrets") == 0)
1946  {
1947  List *parsed_secrets;
1948  char *dupval = pstrdup(val);
1949 
1950  REQUIRE_AUTH_OPTION(uaRADIUS, "radiussecrets", "radius");
1951 
1952  if (!SplitIdentifierString(dupval, ',', &parsed_secrets))
1953  {
1954  /* syntax error in list */
1955  ereport(elevel,
1956  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1957  errmsg("could not parse RADIUS secret list \"%s\"",
1958  val),
1959  errcontext("line %d of configuration file \"%s\"",
1960  line_num, HbaFileName)));
1961  return false;
1962  }
1963 
1964  hbaline->radiussecrets = parsed_secrets;
1965  hbaline->radiussecrets_s = pstrdup(val);
1966  }
1967  else if (strcmp(name, "radiusidentifiers") == 0)
1968  {
1969  List *parsed_identifiers;
1970  char *dupval = pstrdup(val);
1971 
1972  REQUIRE_AUTH_OPTION(uaRADIUS, "radiusidentifiers", "radius");
1973 
1974  if (!SplitIdentifierString(dupval, ',', &parsed_identifiers))
1975  {
1976  /* syntax error in list */
1977  ereport(elevel,
1978  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1979  errmsg("could not parse RADIUS identifiers list \"%s\"",
1980  val),
1981  errcontext("line %d of configuration file \"%s\"",
1982  line_num, HbaFileName)));
1983  return false;
1984  }
1985 
1986  hbaline->radiusidentifiers = parsed_identifiers;
1987  hbaline->radiusidentifiers_s = pstrdup(val);
1988  }
1989  else
1990  {
1991  ereport(elevel,
1992  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1993  errmsg("unrecognized authentication option name: \"%s\"",
1994  name),
1995  errcontext("line %d of configuration file \"%s\"",
1996  line_num, HbaFileName)));
1997  *err_msg = psprintf("unrecognized authentication option name: \"%s\"",
1998  name);
1999  return false;
2000  }
2001  return true;
2002 }
int ldapscope
Definition: hba.h:85
char * radiusports_s
Definition: hba.h:100
Definition: hba.h:30
char * ldapserver
Definition: hba.h:78
#define REQUIRE_AUTH_OPTION(methodval, optname, validmethods)
Definition: hba.c:874
void pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai)
Definition: ip.c:88
Definition: hba.h:38
int ldapport
Definition: hba.h:79
char * ldapbasedn
Definition: hba.h:84
char * pamservice
Definition: hba.h:75
char * pstrdup(const char *in)
Definition: mcxt.c:1076
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
Definition: hba.h:35
#define gettext_noop(x)
Definition: c.h:139
int errcode(int sqlerrcode)
Definition: elog.c:575
#define MemSet(start, val, len)
Definition: c.h:846
List * radiussecrets
Definition: hba.h:95
#define gai_strerror
Definition: getaddrinfo.h:146
char * ldapsuffix
Definition: hba.h:87
char * HbaFileName
Definition: guc.c:463
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
Definition: ip.c:57
#define INVALID_AUTH_OPTION(optname, validmethods)
Definition: hba.c:860
Definition: hba.h:34
ConnType conntype
Definition: hba.h:65
char * radiusservers_s
Definition: hba.h:94
Definition: hba.h:57
bool pam_use_hostname
Definition: hba.h:76
Definition: hba.h:39
char * usermap
Definition: hba.h:74
List * radiusports
Definition: hba.h:99
List * radiusservers
Definition: hba.h:93
bool include_realm
Definition: hba.h:90
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3264
char * ldapbinddn
Definition: hba.h:80
char * krb_realm
Definition: hba.h:89
int linenumber
Definition: hba.h:63
char * ldapbindpasswd
Definition: hba.h:81
#define ereport(elevel, rest)
Definition: elog.h:122
char * ldapprefix
Definition: hba.h:86
static int elevel
Definition: vacuumlazy.c:136
char * radiusidentifiers_s
Definition: hba.h:98
List * radiusidentifiers
Definition: hba.h:97
char * radiussecrets_s
Definition: hba.h:96
#define lfirst(lc)
Definition: pg_list.h:106
char * ldapsearchfilter
Definition: hba.h:83
bool ldaptls
Definition: hba.h:77
char * ldapsearchattribute
Definition: hba.h:82
const char * name
Definition: encode.c:521
bool upn_username
Definition: hba.h:92
int errmsg(const char *fmt,...)
Definition: elog.c:797
void list_free(List *list)
Definition: list.c:1133
#define errcontext
Definition: elog.h:164
bool clientcert
Definition: hba.h:88
Definition: pg_list.h:45
Definition: hba.h:36
bool compat_realm
Definition: hba.h:91
long val
Definition: informix.c:689
Definition: hba.h:40
UserAuth auth_method
Definition: hba.h:72
static HbaLine* parse_hba_line ( TokenizedLine tok_line,
int  elevel 
)
static

Definition at line 945 of file hba.c.

References HbaLine::addr, addrinfo::ai_addr, addrinfo::ai_addrlen, addrinfo::ai_canonname, addrinfo::ai_family, addrinfo::ai_flags, addrinfo::ai_next, AI_NUMERICHOST, addrinfo::ai_protocol, addrinfo::ai_socktype, Assert, HbaLine::auth_method, HbaLine::clientcert, HbaLine::compat_realm, HbaLine::conntype, copy_hba_token(), ctHost, ctHostNoSSL, ctHostSSL, ctLocal, HbaLine::databases, Db_user_namespace, EAI_NONAME, EnableSSL, ereport, TokenizedLine::err_msg, errcode(), errcontext, errhint(), errmsg(), TokenizedLine::fields, gai_strerror, HbaFileName, HbaLine::hostname, HbaLine::include_realm, HbaLine::ip_cmp_method, ipCmpAll, ipCmpMask, ipCmpSameHost, ipCmpSameNet, lappend(), HbaLine::ldapbasedn, HbaLine::ldapbinddn, HbaLine::ldapbindpasswd, HbaLine::ldapprefix, HbaLine::ldapsearchattribute, HbaLine::ldapsearchfilter, HbaLine::ldapserver, HbaLine::ldapsuffix, List::length, lfirst, TokenizedLine::line_num, HbaLine::linenumber, linitial, list_head(), list_length(), lnext, LOG, MANDATORY_AUTH_ARG, HbaLine::mask, NIL, palloc0(), parse_hba_auth_opt(), pfree(), pg_freeaddrinfo_all(), pg_getaddrinfo_all(), pg_sockaddr_cidr_mask(), psprintf(), pstrdup(), HbaLine::radiusidentifiers, HbaLine::radiusports, HbaLine::radiussecrets, HbaLine::radiusservers, TokenizedLine::raw_line, HbaLine::rawline, HbaLine::roles, HbaToken::string, token_is_keyword, uaBSD, uaCert, uaGSS, uaIdent, uaLDAP, uaMD5, uaPAM, uaPassword, uaRADIUS, uaReject, uaSCRAM, uaSSPI, uaTrust, HbaLine::upn_username, val, and verify_option_list_length().

Referenced by fill_hba_view(), and load_hba().

946 {
947  int line_num = tok_line->line_num;
948  char **err_msg = &tok_line->err_msg;
949  char *str;
950  struct addrinfo *gai_result;
951  struct addrinfo hints;
952  int ret;
953  char *cidr_slash;
954  char *unsupauth;
955  ListCell *field;
956  List *tokens;
957  ListCell *tokencell;
958  HbaToken *token;
959  HbaLine *parsedline;
960 
961  parsedline = palloc0(sizeof(HbaLine));
962  parsedline->linenumber = line_num;
963  parsedline->rawline = pstrdup(tok_line->raw_line);
964 
965  /* Check the record type. */
966  Assert(tok_line->fields != NIL);
967  field = list_head(tok_line->fields);
968  tokens = lfirst(field);
969  if (tokens->length > 1)
970  {
971  ereport(elevel,
972  (errcode(ERRCODE_CONFIG_FILE_ERROR),
973  errmsg("multiple values specified for connection type"),
974  errhint("Specify exactly one connection type per line."),
975  errcontext("line %d of configuration file \"%s\"",
976  line_num, HbaFileName)));
977  *err_msg = "multiple values specified for connection type";
978  return NULL;
979  }
980  token = linitial(tokens);
981  if (strcmp(token->string, "local") == 0)
982  {
983 #ifdef HAVE_UNIX_SOCKETS
984  parsedline->conntype = ctLocal;
985 #else
986  ereport(elevel,
987  (errcode(ERRCODE_CONFIG_FILE_ERROR),
988  errmsg("local connections are not supported by this build"),
989  errcontext("line %d of configuration file \"%s\"",
990  line_num, HbaFileName)));
991  *err_msg = "local connections are not supported by this build";
992  return NULL;
993 #endif
994  }
995  else if (strcmp(token->string, "host") == 0 ||
996  strcmp(token->string, "hostssl") == 0 ||
997  strcmp(token->string, "hostnossl") == 0)
998  {
999 
1000  if (token->string[4] == 's') /* "hostssl" */
1001  {
1002  parsedline->conntype = ctHostSSL;
1003  /* Log a warning if SSL support is not active */
1004 #ifdef USE_SSL
1005  if (!EnableSSL)
1006  {
1007  ereport(elevel,
1008  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1009  errmsg("hostssl record cannot match because SSL is disabled"),
1010  errhint("Set ssl = on in postgresql.conf."),
1011  errcontext("line %d of configuration file \"%s\"",
1012  line_num, HbaFileName)));
1013  *err_msg = "hostssl record cannot match because SSL is disabled";
1014  }
1015 #else
1016  ereport(elevel,
1017  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1018  errmsg("hostssl record cannot match because SSL is not supported by this build"),
1019  errhint("Compile with --with-openssl to use SSL connections."),
1020  errcontext("line %d of configuration file \"%s\"",
1021  line_num, HbaFileName)));
1022  *err_msg = "hostssl record cannot match because SSL is not supported by this build";
1023 #endif
1024  }
1025  else if (token->string[4] == 'n') /* "hostnossl" */
1026  {
1027  parsedline->conntype = ctHostNoSSL;
1028  }
1029  else
1030  {
1031  /* "host" */
1032  parsedline->conntype = ctHost;
1033  }
1034  } /* record type */
1035  else
1036  {
1037  ereport(elevel,
1038  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1039  errmsg("invalid connection type \"%s\"",
1040  token->string),
1041  errcontext("line %d of configuration file \"%s\"",
1042  line_num, HbaFileName)));
1043  *err_msg = psprintf("invalid connection type \"%s\"", token->string);
1044  return NULL;
1045  }
1046 
1047  /* Get the databases. */
1048  field = lnext(field);
1049  if (!field)
1050  {
1051  ereport(elevel,
1052  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1053  errmsg("end-of-line before database specification"),
1054  errcontext("line %d of configuration file \"%s\"",
1055  line_num, HbaFileName)));
1056  *err_msg = "end-of-line before database specification";
1057  return NULL;
1058  }
1059  parsedline->databases = NIL;
1060  tokens = lfirst(field);
1061  foreach(tokencell, tokens)
1062  {
1063  parsedline->databases = lappend(parsedline->databases,
1064  copy_hba_token(lfirst(tokencell)));
1065  }
1066 
1067  /* Get the roles. */
1068  field = lnext(field);
1069  if (!field)
1070  {
1071  ereport(elevel,
1072  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1073  errmsg("end-of-line before role specification"),
1074  errcontext("line %d of configuration file \"%s\"",
1075  line_num, HbaFileName)));
1076  *err_msg = "end-of-line before role specification";
1077  return NULL;
1078  }
1079  parsedline->roles = NIL;
1080  tokens = lfirst(field);
1081  foreach(tokencell, tokens)
1082  {
1083  parsedline->roles = lappend(parsedline->roles,
1084  copy_hba_token(lfirst(tokencell)));
1085  }
1086 
1087  if (parsedline->conntype != ctLocal)
1088  {
1089  /* Read the IP address field. (with or without CIDR netmask) */
1090  field = lnext(field);
1091  if (!field)
1092  {
1093  ereport(elevel,
1094  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1095  errmsg("end-of-line before IP address specification"),
1096  errcontext("line %d of configuration file \"%s\"",
1097  line_num, HbaFileName)));
1098  *err_msg = "end-of-line before IP address specification";
1099  return NULL;
1100  }
1101  tokens = lfirst(field);
1102  if (tokens->length > 1)
1103  {
1104  ereport(elevel,
1105  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1106  errmsg("multiple values specified for host address"),
1107  errhint("Specify one address range per line."),
1108  errcontext("line %d of configuration file \"%s\"",
1109  line_num, HbaFileName)));
1110  *err_msg = "multiple values specified for host address";
1111  return NULL;
1112  }
1113  token = linitial(tokens);
1114 
1115  if (token_is_keyword(token, "all"))
1116  {
1117  parsedline->ip_cmp_method = ipCmpAll;
1118  }
1119  else if (token_is_keyword(token, "samehost"))
1120  {
1121  /* Any IP on this host is allowed to connect */
1122  parsedline->ip_cmp_method = ipCmpSameHost;
1123  }
1124  else if (token_is_keyword(token, "samenet"))
1125  {
1126  /* Any IP on the host's subnets is allowed to connect */
1127  parsedline->ip_cmp_method = ipCmpSameNet;
1128  }
1129  else
1130  {
1131  /* IP and netmask are specified */
1132  parsedline->ip_cmp_method = ipCmpMask;
1133 
1134  /* need a modifiable copy of token */
1135  str = pstrdup(token->string);
1136 
1137  /* Check if it has a CIDR suffix and if so isolate it */
1138  cidr_slash = strchr(str, '/');
1139  if (cidr_slash)
1140  *cidr_slash = '\0';
1141 
1142  /* Get the IP address either way */
1143  hints.ai_flags = AI_NUMERICHOST;
1144  hints.ai_family = AF_UNSPEC;
1145  hints.ai_socktype = 0;
1146  hints.ai_protocol = 0;
1147  hints.ai_addrlen = 0;
1148  hints.ai_canonname = NULL;
1149  hints.ai_addr = NULL;
1150  hints.ai_next = NULL;
1151 
1152  ret = pg_getaddrinfo_all(str, NULL, &hints, &gai_result);
1153  if (ret == 0 && gai_result)
1154  memcpy(&parsedline->addr, gai_result->ai_addr,
1155  gai_result->ai_addrlen);
1156  else if (ret == EAI_NONAME)
1157  parsedline->hostname = str;
1158  else
1159  {
1160  ereport(elevel,
1161  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1162  errmsg("invalid IP address \"%s\": %s",
1163  str, gai_strerror(ret)),
1164  errcontext("line %d of configuration file \"%s\"",
1165  line_num, HbaFileName)));
1166  *err_msg = psprintf("invalid IP address \"%s\": %s",
1167  str, gai_strerror(ret));
1168  if (gai_result)
1169  pg_freeaddrinfo_all(hints.ai_family, gai_result);
1170  return NULL;
1171  }
1172 
1173  pg_freeaddrinfo_all(hints.ai_family, gai_result);
1174 
1175  /* Get the netmask */
1176  if (cidr_slash)
1177  {
1178  if (parsedline->hostname)
1179  {
1180  ereport(elevel,
1181  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1182  errmsg("specifying both host name and CIDR mask is invalid: \"%s\"",
1183  token->string),
1184  errcontext("line %d of configuration file \"%s\"",
1185  line_num, HbaFileName)));
1186  *err_msg = psprintf("specifying both host name and CIDR mask is invalid: \"%s\"",
1187  token->string);
1188  return NULL;
1189  }
1190 
1191  if (pg_sockaddr_cidr_mask(&parsedline->mask, cidr_slash + 1,
1192  parsedline->addr.ss_family) < 0)
1193  {
1194  ereport(elevel,
1195  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1196  errmsg("invalid CIDR mask in address \"%s\"",
1197  token->string),
1198  errcontext("line %d of configuration file \"%s\"",
1199  line_num, HbaFileName)));
1200  *err_msg = psprintf("invalid CIDR mask in address \"%s\"",
1201  token->string);
1202  return NULL;
1203  }
1204  pfree(str);
1205  }
1206  else if (!parsedline->hostname)
1207  {
1208  /* Read the mask field. */
1209  pfree(str);
1210  field = lnext(field);
1211  if (!field)
1212  {
1213  ereport(elevel,
1214  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1215  errmsg("end-of-line before netmask specification"),
1216  errhint("Specify an address range in CIDR notation, or provide a separate netmask."),
1217  errcontext("line %d of configuration file \"%s\"",
1218  line_num, HbaFileName)));
1219  *err_msg = "end-of-line before netmask specification";
1220  return NULL;
1221  }
1222  tokens = lfirst(field);
1223  if (tokens->length > 1)
1224  {
1225  ereport(elevel,
1226  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1227  errmsg("multiple values specified for netmask"),
1228  errcontext("line %d of configuration file \"%s\"",
1229  line_num, HbaFileName)));
1230  *err_msg = "multiple values specified for netmask";
1231  return NULL;
1232  }
1233  token = linitial(tokens);
1234 
1235  ret = pg_getaddrinfo_all(token->string, NULL,
1236  &hints, &gai_result);
1237  if (ret || !gai_result)
1238  {
1239  ereport(elevel,
1240  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1241  errmsg("invalid IP mask \"%s\": %s",
1242  token->string, gai_strerror(ret)),
1243  errcontext("line %d of configuration file \"%s\"",
1244  line_num, HbaFileName)));
1245  *err_msg = psprintf("invalid IP mask \"%s\": %s",
1246  token->string, gai_strerror(ret));
1247  if (gai_result)
1248  pg_freeaddrinfo_all(hints.ai_family, gai_result);
1249  return NULL;
1250  }
1251 
1252  memcpy(&parsedline->mask, gai_result->ai_addr,
1253  gai_result->ai_addrlen);
1254  pg_freeaddrinfo_all(hints.ai_family, gai_result);
1255 
1256  if (parsedline->addr.ss_family != parsedline->mask.ss_family)
1257  {
1258  ereport(elevel,
1259  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1260  errmsg("IP address and mask do not match"),
1261  errcontext("line %d of configuration file \"%s\"",
1262  line_num, HbaFileName)));
1263  *err_msg = "IP address and mask do not match";
1264  return NULL;
1265  }
1266  }
1267  }
1268  } /* != ctLocal */
1269 
1270  /* Get the authentication method */
1271  field = lnext(field);
1272  if (!field)
1273  {
1274  ereport(elevel,
1275  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1276  errmsg("end-of-line before authentication method"),
1277  errcontext("line %d of configuration file \"%s\"",
1278  line_num, HbaFileName)));
1279  *err_msg = "end-of-line before authentication method";
1280  return NULL;
1281  }
1282  tokens = lfirst(field);
1283  if (tokens->length > 1)
1284  {
1285  ereport(elevel,
1286  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1287  errmsg("multiple values specified for authentication type"),
1288  errhint("Specify exactly one authentication type per line."),
1289  errcontext("line %d of configuration file \"%s\"",
1290  line_num, HbaFileName)));
1291  *err_msg = "multiple values specified for authentication type";
1292  return NULL;
1293  }
1294  token = linitial(tokens);
1295 
1296  unsupauth = NULL;
1297  if (strcmp(token->string, "trust") == 0)
1298  parsedline->auth_method = uaTrust;
1299  else if (strcmp(token->string, "ident") == 0)
1300  parsedline->auth_method = uaIdent;
1301  else if (strcmp(token->string, "peer") == 0)
1302  parsedline->auth_method = uaPeer;
1303  else if (strcmp(token->string, "password") == 0)
1304  parsedline->auth_method = uaPassword;
1305  else if (strcmp(token->string, "gss") == 0)
1306 #ifdef ENABLE_GSS
1307  parsedline->auth_method = uaGSS;
1308 #else
1309  unsupauth = "gss";
1310 #endif
1311  else if (strcmp(token->string, "sspi") == 0)
1312 #ifdef ENABLE_SSPI
1313  parsedline->auth_method = uaSSPI;
1314 #else
1315  unsupauth = "sspi";
1316 #endif
1317  else if (strcmp(token->string, "reject") == 0)
1318  parsedline->auth_method = uaReject;
1319  else if (strcmp(token->string, "md5") == 0)
1320  {
1321  if (Db_user_namespace)
1322  {
1323  ereport(elevel,
1324  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1325  errmsg("MD5 authentication is not supported when \"db_user_namespace\" is enabled"),
1326  errcontext("line %d of configuration file \"%s\"",
1327  line_num, HbaFileName)));
1328  *err_msg = "MD5 authentication is not supported when \"db_user_namespace\" is enabled";
1329  return NULL;
1330  }
1331  parsedline->auth_method = uaMD5;
1332  }
1333  else if (strcmp(token->string, "scram-sha-256") == 0)
1334  parsedline->auth_method = uaSCRAM;
1335  else if (strcmp(token->string, "pam") == 0)
1336 #ifdef USE_PAM
1337  parsedline->auth_method = uaPAM;
1338 #else
1339  unsupauth = "pam";
1340 #endif
1341  else if (strcmp(token->string, "bsd") == 0)
1342 #ifdef USE_BSD_AUTH
1343  parsedline->auth_method = uaBSD;
1344 #else
1345  unsupauth = "bsd";
1346 #endif
1347  else if (strcmp(token->string, "ldap") == 0)
1348 #ifdef USE_LDAP
1349  parsedline->auth_method = uaLDAP;
1350 #else
1351  unsupauth = "ldap";
1352 #endif
1353  else if (strcmp(token->string, "cert") == 0)
1354 #ifdef USE_SSL
1355  parsedline->auth_method = uaCert;
1356 #else
1357  unsupauth = "cert";
1358 #endif
1359  else if (strcmp(token->string, "radius") == 0)
1360  parsedline->auth_method = uaRADIUS;
1361  else
1362  {
1363  ereport(elevel,
1364  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1365  errmsg("invalid authentication method \"%s\"",
1366  token->string),
1367  errcontext("line %d of configuration file \"%s\"",
1368  line_num, HbaFileName)));
1369  *err_msg = psprintf("invalid authentication method \"%s\"",
1370  token->string);
1371  return NULL;
1372  }
1373 
1374  if (unsupauth)
1375  {
1376  ereport(elevel,
1377  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1378  errmsg("invalid authentication method \"%s\": not supported by this build",
1379  token->string),
1380  errcontext("line %d of configuration file \"%s\"",
1381  line_num, HbaFileName)));
1382  *err_msg = psprintf("invalid authentication method \"%s\": not supported by this build",
1383  token->string);
1384  return NULL;
1385  }
1386 
1387  /*
1388  * XXX: When using ident on local connections, change it to peer, for
1389  * backwards compatibility.
1390  */
1391  if (parsedline->conntype == ctLocal &&
1392  parsedline->auth_method == uaIdent)
1393  parsedline->auth_method = uaPeer;
1394 
1395  /* Invalid authentication combinations */
1396  if (parsedline->conntype == ctLocal &&
1397  parsedline->auth_method == uaGSS)
1398  {
1399  ereport(elevel,
1400  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1401  errmsg("gssapi authentication is not supported on local sockets"),
1402  errcontext("line %d of configuration file \"%s\"",
1403  line_num, HbaFileName)));
1404  *err_msg = "gssapi authentication is not supported on local sockets";
1405  return NULL;
1406  }
1407 
1408  if (parsedline->conntype != ctLocal &&
1409  parsedline->auth_method == uaPeer)
1410  {
1411  ereport(elevel,
1412  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1413  errmsg("peer authentication is only supported on local sockets"),
1414  errcontext("line %d of configuration file \"%s\"",
1415  line_num, HbaFileName)));
1416  *err_msg = "peer authentication is only supported on local sockets";
1417  return NULL;
1418  }
1419 
1420  /*
1421  * SSPI authentication can never be enabled on ctLocal connections,
1422  * because it's only supported on Windows, where ctLocal isn't supported.
1423  */
1424 
1425 
1426  if (parsedline->conntype != ctHostSSL &&
1427  parsedline->auth_method == uaCert)
1428  {
1429  ereport(elevel,
1430  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1431  errmsg("cert authentication is only supported on hostssl connections"),
1432  errcontext("line %d of configuration file \"%s\"",
1433  line_num, HbaFileName)));
1434  *err_msg = "cert authentication is only supported on hostssl connections";
1435  return NULL;
1436  }
1437 
1438  /*
1439  * For GSS and SSPI, set the default value of include_realm to true.
1440  * Having include_realm set to false is dangerous in multi-realm
1441  * situations and is generally considered bad practice. We keep the
1442  * capability around for backwards compatibility, but we might want to
1443  * remove it at some point in the future. Users who still need to strip
1444  * the realm off would be better served by using an appropriate regex in a
1445  * pg_ident.conf mapping.
1446  */
1447  if (parsedline->auth_method == uaGSS ||
1448  parsedline->auth_method == uaSSPI)
1449  parsedline->include_realm = true;
1450 
1451  /*
1452  * For SSPI, include_realm defaults to the SAM-compatible domain (aka
1453  * NetBIOS name) and user names instead of the Kerberos principal name for
1454  * compatibility.
1455  */
1456  if (parsedline->auth_method == uaSSPI)
1457  {
1458  parsedline->compat_realm = true;
1459  parsedline->upn_username = false;
1460  }
1461 
1462  /* Parse remaining arguments */
1463  while ((field = lnext(field)) != NULL)
1464  {
1465  tokens = lfirst(field);
1466  foreach(tokencell, tokens)
1467  {
1468  char *val;
1469 
1470  token = lfirst(tokencell);
1471 
1472  str = pstrdup(token->string);
1473  val = strchr(str, '=');
1474  if (val == NULL)
1475  {
1476  /*
1477  * Got something that's not a name=value pair.
1478  */
1479  ereport(elevel,
1480  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1481  errmsg("authentication option not in name=value format: %s", token->string),
1482  errcontext("line %d of configuration file \"%s\"",
1483  line_num, HbaFileName)));
1484  *err_msg = psprintf("authentication option not in name=value format: %s",
1485  token->string);
1486  return NULL;
1487  }
1488 
1489  *val++ = '\0'; /* str now holds "name", val holds "value" */
1490  if (!parse_hba_auth_opt(str, val, parsedline, elevel, err_msg))
1491  /* parse_hba_auth_opt already logged the error message */
1492  return NULL;
1493  pfree(str);
1494  }
1495  }
1496 
1497  /*
1498  * Check if the selected authentication method has any mandatory arguments
1499  * that are not set.
1500  */
1501  if (parsedline->auth_method == uaLDAP)
1502  {
1503  MANDATORY_AUTH_ARG(parsedline->ldapserver, "ldapserver", "ldap");
1504 
1505  /*
1506  * LDAP can operate in two modes: either with a direct bind, using
1507  * ldapprefix and ldapsuffix, or using a search+bind, using
1508  * ldapbasedn, ldapbinddn, ldapbindpasswd and one of
1509  * ldapsearchattribute or ldapsearchfilter. Disallow mixing these
1510  * parameters.
1511  */
1512  if (parsedline->ldapprefix || parsedline->ldapsuffix)
1513  {
1514  if (parsedline->ldapbasedn ||
1515  parsedline->ldapbinddn ||
1516  parsedline->ldapbindpasswd ||
1517  parsedline->ldapsearchattribute ||
1518  parsedline->ldapsearchfilter)
1519  {
1520  ereport(elevel,
1521  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1522  errmsg("cannot use ldapbasedn, ldapbinddn, ldapbindpasswd, ldapsearchattribute, ldapsearchfilter or ldapurl together with ldapprefix"),
1523  errcontext("line %d of configuration file \"%s\"",
1524  line_num, HbaFileName)));
1525  *err_msg = "cannot use ldapbasedn, ldapbinddn, ldapbindpasswd, ldapsearchattribute, ldapsearchfilter or ldapurl together with ldapprefix";
1526  return NULL;
1527  }
1528  }
1529  else if (!parsedline->ldapbasedn)
1530  {
1531  ereport(elevel,
1532  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1533  errmsg("authentication method \"ldap\" requires argument \"ldapbasedn\", \"ldapprefix\", or \"ldapsuffix\" to be set"),
1534  errcontext("line %d of configuration file \"%s\"",
1535  line_num, HbaFileName)));
1536  *err_msg = "authentication method \"ldap\" requires argument \"ldapbasedn\", \"ldapprefix\", or \"ldapsuffix\" to be set";
1537  return NULL;
1538  }
1539 
1540  /*
1541  * When using search+bind, you can either use a simple attribute
1542  * (defaulting to "uid") or a fully custom search filter. You can't
1543  * do both.
1544  */
1545  if (parsedline->ldapsearchattribute && parsedline->ldapsearchfilter)
1546  {
1547  ereport(elevel,
1548  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1549  errmsg("cannot use ldapsearchattribute together with ldapsearchfilter"),
1550  errcontext("line %d of configuration file \"%s\"",
1551  line_num, HbaFileName)));
1552  *err_msg = "cannot use ldapsearchattribute together with ldapsearchfilter";
1553  return NULL;
1554  }
1555  }
1556 
1557  if (parsedline->auth_method == uaRADIUS)
1558  {
1559  MANDATORY_AUTH_ARG(parsedline->radiusservers, "radiusservers", "radius");
1560  MANDATORY_AUTH_ARG(parsedline->radiussecrets, "radiussecrets", "radius");
1561 
1562  if (list_length(parsedline->radiusservers) < 1)
1563  {
1564  ereport(LOG,
1565  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1566  errmsg("list of RADIUS servers cannot be empty"),
1567  errcontext("line %d of configuration file \"%s\"",
1568  line_num, HbaFileName)));
1569  return NULL;
1570  }
1571 
1572  if (list_length(parsedline->radiussecrets) < 1)
1573  {
1574  ereport(LOG,
1575  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1576  errmsg("list of RADIUS secrets cannot be empty"),
1577  errcontext("line %d of configuration file \"%s\"",
1578  line_num, HbaFileName)));
1579  return NULL;
1580  }
1581 
1582  /*
1583  * Verify length of option lists - each can be 0 (except for secrets,
1584  * but that's already checked above), 1 (use the same value
1585  * everywhere) or the same as the number of servers.
1586  */
1587  if (!verify_option_list_length(parsedline->radiussecrets,
1588  "RADIUS secrets",
1589  parsedline->radiusservers,
1590  "RADIUS servers",
1591  line_num))
1592  return NULL;
1593  if (!verify_option_list_length(parsedline->radiusports,
1594  "RADIUS ports",
1595  parsedline->radiusservers,
1596  "RADIUS servers",
1597  line_num))
1598  return NULL;
1600  "RADIUS identifiers",
1601  parsedline->radiusservers,
1602  "RADIUS servers",
1603  line_num))
1604  return NULL;
1605  }
1606 
1607  /*
1608  * Enforce any parameters implied by other settings.
1609  */
1610  if (parsedline->auth_method == uaCert)
1611  {
1612  parsedline->clientcert = true;
1613  }
1614 
1615  return parsedline;
1616 }
List * databases
Definition: hba.h:66
Definition: hba.h:61
#define NIL
Definition: pg_list.h:69
Definition: hba.h:30
bool EnableSSL
Definition: postmaster.c:234
char * ldapserver
Definition: hba.h:78
void pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai)
Definition: ip.c:88
struct sockaddr_storage mask
Definition: hba.h:69
int errhint(const char *fmt,...)
Definition: elog.c:987
Definition: hba.h:38
char * ldapbasedn
Definition: hba.h:84
Definition: hba.h:32
static bool parse_hba_auth_opt(char *name, char *val, HbaLine *hbaline, int elevel, char **err_msg)
Definition: hba.c:1647
Definition: hba.h:47
char * pstrdup(const char *in)
Definition: mcxt.c:1076
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
Definition: hba.h:35
int errcode(int sqlerrcode)
Definition: elog.c:575
#define LOG
Definition: elog.h:26
#define AI_NUMERICHOST
Definition: getaddrinfo.h:73
List * radiussecrets
Definition: hba.h:95
#define gai_strerror
Definition: getaddrinfo.h:146
char * ldapsuffix
Definition: hba.h:87
char * HbaFileName
Definition: guc.c:463
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
Definition: ip.c:57
Definition: hba.h:34
Definition: hba.h:31
ConnType conntype
Definition: hba.h:65
void pfree(void *pointer)
Definition: mcxt.c:949
Definition: hba.h:57
#define linitial(l)
Definition: pg_list.h:111
Definition: hba.h:39
int pg_sockaddr_cidr_mask(struct sockaddr_storage *mask, char *numbits, int family)
Definition: ifaddr.c:115
struct sockaddr_storage addr
Definition: hba.h:68
int line_num
Definition: hba.c:92
List * radiusports
Definition: hba.h:99
Definition: hba.h:27
List * radiusservers
Definition: hba.h:93
bool include_realm
Definition: hba.h:90
Definition: hba.h:29
bool Db_user_namespace
Definition: postmaster.c:241
char * err_msg
Definition: hba.c:94
Definition: hba.c:75
char * ldapbinddn
Definition: hba.h:80
#define EAI_NONAME
Definition: getaddrinfo.h:34
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
int linenumber
Definition: hba.h:63
#define MANDATORY_AUTH_ARG(argvar, argname, authname)
Definition: hba.c:880
char * ldapbindpasswd
Definition: hba.h:81
List * fields
Definition: hba.c:91
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
char * ldapprefix
Definition: hba.h:86
Definition: hba.h:55
List * lappend(List *list, void *datum)
Definition: list.c:128
static int elevel
Definition: vacuumlazy.c:136
static bool verify_option_list_length(List *options, char *optionname, List *masters, char *mastername, int line_num)
Definition: hba.c:1620
Definition: hba.h:33
Definition: hba.h:50
void * palloc0(Size size)
Definition: mcxt.c:877
char * hostname
Definition: hba.h:71
char * string
Definition: hba.c:77
List * radiusidentifiers
Definition: hba.h:97
Definition: hba.h:37
List * roles
Definition: hba.h:67
#define Assert(condition)
Definition: c.h:664
#define lfirst(lc)
Definition: pg_list.h:106
char * ldapsearchfilter
Definition: hba.h:83
static int list_length(const List *l)
Definition: pg_list.h:89
char * ldapsearchattribute
Definition: hba.h:82
int length
Definition: pg_list.h:48
char * rawline
Definition: hba.h:64
static HbaToken * copy_hba_token(HbaToken *in)
Definition: hba.c:307
bool upn_username
Definition: hba.h:92
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define token_is_keyword(t, k)
Definition: hba.c:68
#define errcontext
Definition: elog.h:164
bool clientcert
Definition: hba.h:88
size_t ai_addrlen
Definition: getaddrinfo.h:104
char * raw_line
Definition: hba.c:93
IPCompareMethod ip_cmp_method
Definition: hba.h:70
Definition: pg_list.h:45
Definition: hba.h:36
bool compat_realm
Definition: hba.h:91
long val
Definition: informix.c:689
Definition: hba.h:56
Definition: hba.h:40
UserAuth auth_method
Definition: hba.h:72
struct sockaddr * ai_addr
Definition: getaddrinfo.h:105
static IdentLine* parse_ident_line ( TokenizedLine tok_line)
static

Definition at line 2629 of file hba.c.

References Assert, C_COLLATION_OID, ereport, errcode(), errmsg(), TokenizedLine::fields, IDENT_FIELD_ABSENT, IDENT_MULTI_VALUE, IdentLine::ident_user, lfirst, TokenizedLine::line_num, IdentLine::linenumber, linitial, list_head(), lnext, LOG, NIL, palloc(), palloc0(), pfree(), pg_mb2wchar_with_len(), pg_regcomp(), pg_regerror(), IdentLine::pg_role, pstrdup(), IdentLine::re, REG_ADVANCED, HbaToken::string, and IdentLine::usermap.

Referenced by load_ident().

2630 {
2631  int line_num = tok_line->line_num;
2632  ListCell *field;
2633  List *tokens;
2634  HbaToken *token;
2635  IdentLine *parsedline;
2636 
2637  Assert(tok_line->fields != NIL);
2638  field = list_head(tok_line->fields);
2639 
2640  parsedline = palloc0(sizeof(IdentLine));
2641  parsedline->linenumber = line_num;
2642 
2643  /* Get the map token (must exist) */
2644  tokens = lfirst(field);
2645  IDENT_MULTI_VALUE(tokens);
2646  token = linitial(tokens);
2647  parsedline->usermap = pstrdup(token->string);
2648 
2649  /* Get the ident user token */
2650  field = lnext(field);
2651  IDENT_FIELD_ABSENT(field);
2652  tokens = lfirst(field);
2653  IDENT_MULTI_VALUE(tokens);
2654  token = linitial(tokens);
2655  parsedline->ident_user = pstrdup(token->string);
2656 
2657  /* Get the PG rolename token */
2658  field = lnext(field);
2659  IDENT_FIELD_ABSENT(field);
2660  tokens = lfirst(field);
2661  IDENT_MULTI_VALUE(tokens);
2662  token = linitial(tokens);
2663  parsedline->pg_role = pstrdup(token->string);
2664 
2665  if (parsedline->ident_user[0] == '/')
2666  {
2667  /*
2668  * When system username starts with a slash, treat it as a regular
2669  * expression. Pre-compile it.
2670  */
2671  int r;
2672  pg_wchar *wstr;
2673  int wlen;
2674 
2675  wstr = palloc((strlen(parsedline->ident_user + 1) + 1) * sizeof(pg_wchar));
2676  wlen = pg_mb2wchar_with_len(parsedline->ident_user + 1,
2677  wstr, strlen(parsedline->ident_user + 1));
2678 
2679  r = pg_regcomp(&parsedline->re, wstr, wlen, REG_ADVANCED, C_COLLATION_OID);
2680  if (r)
2681  {
2682  char errstr[100];
2683 
2684  pg_regerror(r, &parsedline->re, errstr, sizeof(errstr));
2685  ereport(LOG,
2686  (errcode(ERRCODE_INVALID_REGULAR_EXPRESSION),
2687  errmsg("invalid regular expression \"%s\": %s",
2688  parsedline->ident_user + 1, errstr)));
2689 
2690  pfree(wstr);
2691  return NULL;
2692  }
2693  pfree(wstr);
2694  }
2695 
2696  return parsedline;
2697 }
#define NIL
Definition: pg_list.h:69
regex_t re
Definition: hba.h:110
char * pstrdup(const char *in)
Definition: mcxt.c:1076
int errcode(int sqlerrcode)
Definition: elog.c:575
#define LOG
Definition: elog.h:26
int pg_regcomp(regex_t *re, const chr *string, size_t len, int flags, Oid collation)
Definition: regcomp.c:314
#define IDENT_FIELD_ABSENT(field)
Definition: hba.c:908
int linenumber
Definition: hba.h:105
void pfree(void *pointer)
Definition: mcxt.c:949
#define linitial(l)
Definition: pg_list.h:111
int line_num
Definition: hba.c:92
char * usermap
Definition: hba.h:107
Definition: hba.c:75
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
size_t pg_regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)
Definition: regerror.c:60
#define REG_ADVANCED
Definition: regex.h:103
List * fields
Definition: hba.c:91
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
unsigned int pg_wchar
Definition: mbprint.c:31
#define IDENT_MULTI_VALUE(tokens)
Definition: hba.c:919
void * palloc0(Size size)
Definition: mcxt.c:877
char * string
Definition: hba.c:77
int pg_mb2wchar_with_len(const char *from, pg_wchar *to, int len)
Definition: mbutils.c:734
#define Assert(condition)
Definition: c.h:664
#define lfirst(lc)
Definition: pg_list.h:106
Definition: hba.h:103
#define C_COLLATION_OID
Definition: pg_collation.h:78
char * ident_user
Definition: hba.h:108
void * palloc(Size size)
Definition: mcxt.c:848
int errmsg(const char *fmt,...)
Definition: elog.c:797
Definition: pg_list.h:45
char * pg_role
Definition: hba.h:109
Datum pg_hba_file_rules ( PG_FUNCTION_ARGS  )

Definition at line 2566 of file hba.c.

References ReturnSetInfo::allowedModes, ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, elog, ereport, errcode(), errmsg(), ERROR, fill_hba_view(), get_call_result_type(), IsA, MemoryContextSwitchTo(), PG_RETURN_NULL, ReturnSetInfo::returnMode, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, SFRM_Materialize_Random, tuplestore_begin_heap(), TYPEFUNC_COMPOSITE, and work_mem.

2567 {
2568  Tuplestorestate *tuple_store;
2569  TupleDesc tupdesc;
2570  MemoryContext old_cxt;
2571  ReturnSetInfo *rsi;
2572 
2573  /*
2574  * We must use the Materialize mode to be safe against HBA file changes
2575  * while the cursor is open. It's also more efficient than having to look
2576  * up our current position in the parsed list every time.
2577  */
2578  rsi = (ReturnSetInfo *) fcinfo->resultinfo;
2579 
2580  /* Check to see if caller supports us returning a tuplestore */
2581  if (rsi == NULL || !IsA(rsi, ReturnSetInfo))
2582  ereport(ERROR,
2583  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2584  errmsg("set-valued function called in context that cannot accept a set")));
2585  if (!(rsi->allowedModes & SFRM_Materialize))
2586  ereport(ERROR,
2587  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2588  errmsg("materialize mode required, but it is not " \
2589  "allowed in this context")));
2590 
2592 
2593  /* Build a tuple descriptor for our result type */
2594  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
2595  elog(ERROR, "return type must be a row type");
2596 
2597  /* Build tuplestore to hold the result rows */
2599 
2600  tuple_store =
2602  false, work_mem);
2603  rsi->setDesc = tupdesc;
2604  rsi->setResult = tuple_store;
2605 
2606  MemoryContextSwitchTo(old_cxt);
2607 
2608  /* Fill the tuplestore */
2609  fill_hba_view(tuple_store, tupdesc);
2610 
2611  PG_RETURN_NULL();
2612 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:211
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
static void fill_hba_view(Tuplestorestate *tuple_store, TupleDesc tupdesc)
Definition: hba.c:2512
int work_mem
Definition: globals.c:113
int allowedModes
Definition: execnodes.h:268
SetFunctionReturnMode returnMode
Definition: execnodes.h:270
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:202
Tuplestorestate * setResult
Definition: execnodes.h:273
ExprContext * econtext
Definition: execnodes.h:266
TupleDesc setDesc
Definition: execnodes.h:274
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
#define PG_RETURN_NULL()
Definition: fmgr.h:305
bool pg_isblank ( const char  c)

Definition at line 160 of file hba.c.

Referenced by interpret_ident_response(), and next_token().

161 {
162  return c == ' ' || c == '\t' || c == '\r';
163 }
char * c
static MemoryContext tokenize_file ( const char *  filename,
FILE *  file,
List **  tok_lines,
int  elevel 
)
static

Definition at line 470 of file hba.c.

References ALLOCSET_SMALL_SIZES, AllocSetContextCreate(), CurrentMemoryContext, ereport, TokenizedLine::err_msg, errcode(), errcode_for_file_access(), errcontext, errmsg(), TokenizedLine::fields, lappend(), TokenizedLine::line_num, MAX_LINE, MemoryContextSwitchTo(), next_field_expand(), NIL, palloc(), psprintf(), pstrdup(), TokenizedLine::raw_line, and strerror().

Referenced by fill_hba_view(), load_hba(), load_ident(), and tokenize_inc_file().

471 {
472  int line_number = 1;
473  MemoryContext linecxt;
474  MemoryContext oldcxt;
475 
477  "tokenize_file",
479  oldcxt = MemoryContextSwitchTo(linecxt);
480 
481  *tok_lines = NIL;
482 
483  while (!feof(file) && !ferror(file))
484  {
485  char rawline[MAX_LINE];
486  char *lineptr;
487  List *current_line = NIL;
488  char *err_msg = NULL;
489 
490  if (!fgets(rawline, sizeof(rawline), file))
491  {
492  int save_errno = errno;
493 
494  if (!ferror(file))
495  break; /* normal EOF */
496  /* I/O error! */
497  ereport(elevel,
499  errmsg("could not read file \"%s\": %m", filename)));
500  err_msg = psprintf("could not read file \"%s\": %s",
501  filename, strerror(save_errno));
502  rawline[0] = '\0';
503  }
504  if (strlen(rawline) == MAX_LINE - 1)
505  {
506  /* Line too long! */
507  ereport(elevel,
508  (errcode(ERRCODE_CONFIG_FILE_ERROR),
509  errmsg("authentication file line too long"),
510  errcontext("line %d of configuration file \"%s\"",
511  line_number, filename)));
512  err_msg = "authentication file line too long";
513  }
514 
515  /* Strip trailing linebreak from rawline */
516  lineptr = rawline + strlen(rawline) - 1;
517  while (lineptr >= rawline && (*lineptr == '\n' || *lineptr == '\r'))
518  *lineptr-- = '\0';
519 
520  /* Parse fields */
521  lineptr = rawline;
522  while (*lineptr && err_msg == NULL)
523  {
524  List *current_field;
525 
526  current_field = next_field_expand(filename, &lineptr,
527  elevel, &err_msg);
528  /* add field to line, unless we are at EOL or comment start */
529  if (current_field != NIL)
530  current_line = lappend(current_line, current_field);
531  }
532 
533  /* Reached EOL; emit line to TokenizedLine list unless it's boring */
534  if (current_line != NIL || err_msg != NULL)
535  {
536  TokenizedLine *tok_line;
537 
538  tok_line = (TokenizedLine *) palloc(sizeof(TokenizedLine));
539  tok_line->fields = current_line;
540  tok_line->line_num = line_number;
541  tok_line->raw_line = pstrdup(rawline);
542  tok_line->err_msg = err_msg;
543  *tok_lines = lappend(*tok_lines, tok_line);
544  }
545 
546  line_number++;
547  }
548 
549  MemoryContextSwitchTo(oldcxt);
550 
551  return linecxt;
552 }
#define NIL
Definition: pg_list.h:69
char * pstrdup(const char *in)
Definition: mcxt.c:1076
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:175
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:575
int line_num
Definition: hba.c:92
char * err_msg
Definition: hba.c:94
int errcode_for_file_access(void)
Definition: elog.c:598
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
List * fields
Definition: hba.c:91
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
#define MAX_LINE
Definition: hba.c:57
static int elevel
Definition: vacuumlazy.c:136
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
static char * filename
Definition: pg_dumpall.c:90
void * palloc(Size size)
Definition: mcxt.c:848
int errmsg(const char *fmt,...)
Definition: elog.c:797
const char * strerror(int errnum)
Definition: strerror.c:19
#define errcontext
Definition: elog.h:164
char * raw_line
Definition: hba.c:93
Definition: pg_list.h:45
static List * next_field_expand(const char *filename, char **lineptr, int elevel, char **err_msg)
Definition: hba.c:330
static List * tokenize_inc_file ( List tokens,
const char *  outer_filename,
const char *  inc_filename,
int  elevel,
char **  err_msg 
)
static

Definition at line 372 of file hba.c.

References AllocateFile(), canonicalize_path(), copy_hba_token(), ereport, TokenizedLine::err_msg, errcode_for_file_access(), errmsg(), TokenizedLine::fields, FreeFile(), get_parent_directory(), is_absolute_path, join_path_components(), lappend(), lfirst, MemoryContextDelete(), palloc(), pfree(), psprintf(), pstrdup(), strerror(), and tokenize_file().

Referenced by next_field_expand().

377 {
378  char *inc_fullname;
379  FILE *inc_file;
380  List *inc_lines;
381  ListCell *inc_line;
382  MemoryContext linecxt;
383 
384  if (is_absolute_path(inc_filename))
385  {
386  /* absolute path is taken as-is */
387  inc_fullname = pstrdup(inc_filename);
388  }
389  else
390  {
391  /* relative path is relative to dir of calling file */
392  inc_fullname = (char *) palloc(strlen(outer_filename) + 1 +
393  strlen(inc_filename) + 1);
394  strcpy(inc_fullname, outer_filename);
395  get_parent_directory(inc_fullname);
396  join_path_components(inc_fullname, inc_fullname, inc_filename);
397  canonicalize_path(inc_fullname);
398  }
399 
400  inc_file = AllocateFile(inc_fullname, "r");
401  if (inc_file == NULL)
402  {
403  int save_errno = errno;
404 
405  ereport(elevel,
407  errmsg("could not open secondary authentication file \"@%s\" as \"%s\": %m",
408  inc_filename, inc_fullname)));
409  *err_msg = psprintf("could not open secondary authentication file \"@%s\" as \"%s\": %s",
410  inc_filename, inc_fullname, strerror(save_errno));
411  pfree(inc_fullname);
412  return tokens;
413  }
414 
415  /* There is possible recursion here if the file contains @ */
416  linecxt = tokenize_file(inc_fullname, inc_file, &inc_lines, elevel);
417 
418  FreeFile(inc_file);
419  pfree(inc_fullname);
420 
421  /* Copy all tokens found in the file and append to the tokens list */
422  foreach(inc_line, inc_lines)
423  {
424  TokenizedLine *tok_line = (TokenizedLine *) lfirst(inc_line);
425  ListCell *inc_field;
426 
427  /* If any line has an error, propagate that up to caller */
428  if (tok_line->err_msg)
429  {
430  *err_msg = pstrdup(tok_line->err_msg);
431  break;
432  }
433 
434  foreach(inc_field, tok_line->fields)
435  {
436  List *inc_tokens = lfirst(inc_field);
437  ListCell *inc_token;
438 
439  foreach(inc_token, inc_tokens)
440  {
441  HbaToken *token = lfirst(inc_token);
442 
443  tokens = lappend(tokens, copy_hba_token(token));
444  }
445  }
446  }
447 
448  MemoryContextDelete(linecxt);
449  return tokens;
450 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
char * pstrdup(const char *in)
Definition: mcxt.c:1076
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
void canonicalize_path(char *path)
Definition: path.c:254
void pfree(void *pointer)
Definition: mcxt.c:949
char * err_msg
Definition: hba.c:94
Definition: hba.c:75
int errcode_for_file_access(void)
Definition: elog.c:598
#define is_absolute_path(filename)
Definition: port.h:77
void get_parent_directory(char *path)
Definition: path.c:854
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2117
List * fields
Definition: hba.c:91
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
static int elevel
Definition: vacuumlazy.c:136
#define lfirst(lc)
Definition: pg_list.h:106
static MemoryContext tokenize_file(const char *filename, FILE *file, List **tok_lines, int elevel)
Definition: hba.c:470
void join_path_components(char *ret_path, const char *head, const char *tail)
Definition: path.c:218
static HbaToken * copy_hba_token(HbaToken *in)
Definition: hba.c:307
int FreeFile(FILE *file)
Definition: fd.c:2309
void * palloc(Size size)
Definition: mcxt.c:848
int errmsg(const char *fmt,...)
Definition: elog.c:797
const char * strerror(int errnum)
Definition: strerror.c:19
Definition: pg_list.h:45
static bool verify_option_list_length ( List options,
char *  optionname,
List masters,
char *  mastername,
int  line_num 
)
static

Definition at line 1620 of file hba.c.

References ereport, errcode(), errcontext, errmsg(), HbaFileName, list_length(), and LOG.

Referenced by parse_hba_line().

1621 {
1622  if (list_length(options) == 0 ||
1623  list_length(options) == 1 ||
1624  list_length(options) == list_length(masters))
1625  return true;
1626 
1627  ereport(LOG,
1628  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1629  errmsg("the number of %s (%d) must be 1 or the same as the number of %s (%d)",
1630  optionname,
1631  list_length(options),
1632  mastername,
1633  list_length(masters)
1634  ),
1635  errcontext("line %d of configuration file \"%s\"",
1636  line_num, HbaFileName)));
1637  return false;
1638 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define LOG
Definition: elog.h:26
char * HbaFileName
Definition: guc.c:463
#define ereport(elevel, rest)
Definition: elog.h:122
static int list_length(const List *l)
Definition: pg_list.h:89
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define errcontext
Definition: elog.h:164

Variable Documentation

MemoryContext parsed_hba_context = NULL
static

Definition at line 102 of file hba.c.

List* parsed_hba_lines = NIL
static

Definition at line 101 of file hba.c.

MemoryContext parsed_ident_context = NULL
static

Definition at line 113 of file hba.c.

List* parsed_ident_lines = NIL
static

Definition at line 112 of file hba.c.

const char* const UserAuthName[]
static
Initial value:
=
{
"reject",
"implicit reject",
"trust",
"ident",
"password",
"md5",
"scram-sha256",
"gss",
"sspi",
"pam",
"bsd",
"ldap",
"cert",
"radius",
"peer"
}

Definition at line 121 of file hba.c.

Referenced by fill_hba_line().