1 /*-------------------------------------------------------------------------
4 * Routines to handle host based authentication (that's the scheme
5 * wherein you authenticate a user by seeing what IP address the system
6 * says he comes from and possibly using ident).
8 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
9 * Portions Copyright (c) 1994, Regents of the University of California
13 * $PostgreSQL: pgsql/src/backend/libpq/hba.c,v 1.125 2004/05/30 23:40:26 neilc Exp $
15 *-------------------------------------------------------------------------
22 #include <sys/param.h>
23 #include <sys/socket.h>
24 #if defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED)
26 #include <sys/ucred.h>
28 #include <netinet/in.h>
29 #include <arpa/inet.h>
32 #include "commands/user.h"
33 #include "libpq/crypt.h"
34 #include "libpq/libpq.h"
35 #include "miscadmin.h"
36 #include "nodes/pg_list.h"
37 #include "storage/fd.h"
40 /* Max size of username ident server can return */
41 #define IDENT_USERNAME_MAX 512
43 /* Standard TCP port number for Ident service. Assigned by IANA */
44 #define IDENT_PORT 113
46 /* Name of the config file */
47 #define CONF_FILE "pg_hba.conf"
49 /* Name of the usermap file */
50 #define USERMAP_FILE "pg_ident.conf"
52 /* This is used to separate values in multi-valued column strings */
53 #define MULTI_VALUE_SEP "\001"
58 * These variables hold the pre-parsed contents of the hba and ident
59 * configuration files. Each is a list of sublists, one sublist for
60 * each (non-empty, non-comment) line of the file. Each sublist's
61 * first item is an integer line number (so we can give somewhat-useful
62 * location info in error messages). Remaining items are palloc'd strings,
63 * one string per token on the line. Note there will always be at least
64 * one token, since blank lines are not entered in the data structure.
67 /* pre-parsed content of CONF_FILE and corresponding line #s */
68 static List *hba_lines = NIL;
69 static List *hba_line_nums = NIL;
70 /* pre-parsed content of USERMAP_FILE and corresponding line #s */
71 static List *ident_lines = NIL;
72 static List *ident_line_nums = NIL;
73 /* pre-parsed content of group file and corresponding line #s */
74 static List *group_lines = NIL;
75 static List *group_line_nums = NIL;
76 /* pre-parsed content of user passwd file and corresponding line #s */
77 static List *user_lines = NIL;
78 static List *user_line_nums = NIL;
80 /* sorted entries so we can do binary search lookups */
81 static List **user_sorted = NULL; /* sorted user list, for bsearch() */
82 static List **group_sorted = NULL; /* sorted group list, for
84 static int user_length;
85 static int group_length;
87 static void tokenize_file(FILE *file, List **lines, List **line_nums);
88 static char *tokenize_inc_file(const char *inc_filename);
91 * isblank() exists in the ISO C99 spec, but it's not very portable yet,
92 * so provide our own version.
95 pg_isblank(const char c)
97 return c == ' ' || c == '\t' || c == '\r';
102 * Grab one token out of fp. Tokens are strings of non-blank
103 * characters bounded by blank characters, beginning of line, and
104 * end of line. Blank means space or tab. Return the token as
105 * *buf. Leave file positioned at the character immediately after the
106 * token or EOF, whichever comes first. If no more tokens on line,
107 * return empty string as *buf and position the file to the beginning
108 * of the next line or EOF, whichever comes first. Allow spaces in
109 * quoted strings. Terminate on unquoted commas. Handle
110 * comments. Treat unquoted keywords that might be user names or
111 * database names specially, by appending a newline to them.
114 next_token(FILE *fp, char *buf, int bufsz)
117 char *start_buf = buf;
118 char *end_buf = buf + (bufsz - 2);
119 bool in_quote = false;
120 bool was_quote = false;
121 bool saw_quote = false;
123 Assert(end_buf > start_buf);
125 /* Move over initial whitespace and commas */
126 while ((c = getc(fp)) != EOF && (pg_isblank(c) || c == ','))
129 if (c == EOF || c == '\n')
136 * Build a token in buf of next characters up to EOF, EOL,
137 * unquoted comma, or unquoted whitespace.
139 while (c != EOF && c != '\n' &&
140 (!pg_isblank(c) || in_quote == true))
142 /* skip comments to EOL */
143 if (c == '#' && !in_quote)
145 while ((c = getc(fp)) != EOF && c != '\n')
147 /* If only comment, consume EOL too; return EOL */
148 if (c != EOF && buf == start_buf)
157 (errcode(ERRCODE_CONFIG_FILE_ERROR),
158 errmsg("authentication file token too long, skipping: \"%s\"",
160 /* Discard remainder of line */
161 while ((c = getc(fp)) != EOF && c != '\n')
166 if (c != '"' || (c == '"' && was_quote))
169 /* We pass back the comma so the caller knows there is more */
170 if ((pg_isblank(c) || c == ',') && !in_quote)
173 /* Literal double-quote is two double-quotes */
174 if (in_quote && c == '"')
175 was_quote = !was_quote;
181 in_quote = !in_quote;
189 * Put back the char right after the token (critical in case it is
190 * EOL, since we need to detect end-of-line at next call).
198 (strcmp(start_buf, "all") == 0 ||
199 strcmp(start_buf, "sameuser") == 0 ||
200 strcmp(start_buf, "samegroup") == 0))
202 /* append newline to a magical keyword */
209 * Tokenize file and handle file inclusion and comma lists. We have
210 * to break apart the commas to expand any file names then
211 * reconstruct with commas.
214 next_token_expand(FILE *file)
217 char *comma_str = pstrdup("");
223 next_token(file, buf, sizeof(buf));
227 if (buf[strlen(buf) - 1] == ',')
229 trailing_comma = true;
230 buf[strlen(buf) - 1] = '\0';
233 trailing_comma = false;
235 /* Is this referencing a file? */
237 incbuf = tokenize_inc_file(buf + 1);
239 incbuf = pstrdup(buf);
241 comma_str = repalloc(comma_str,
242 strlen(comma_str) + strlen(incbuf) + 1);
243 strcat(comma_str, incbuf);
248 comma_str = repalloc(comma_str, strlen(comma_str) + 1 + 1);
249 strcat(comma_str, MULTI_VALUE_SEP);
251 } while (trailing_comma);
258 * Free memory used by lines/tokens (i.e., structure built by tokenize_file)
261 free_lines(List **lines, List **line_nums)
264 * Either both must be non-NULL, or both must be NULL
266 Assert((*lines != NIL && *line_nums != NIL) ||
267 (*lines == NIL && *line_nums == NIL));
272 * "lines" is a list of lists; each of those sublists consists
273 * of palloc'ed tokens, so we want to free each pointed-to
274 * token in a sublist, followed by the sublist itself, and
275 * finally the whole list.
279 foreach(line, *lines)
281 List *ln = lfirst(line);
285 pfree(lfirst(token));
286 /* free the sublist structure itself */
289 /* free the list structure itself */
291 /* clear the static variable */
297 list_free(*line_nums);
304 tokenize_inc_file(const char *inc_filename)
311 char *comma_str = pstrdup("");
313 inc_fullname = (char *) palloc(strlen(DataDir) + 1 +
314 strlen(inc_filename) + 1);
315 strcpy(inc_fullname, DataDir);
316 strcat(inc_fullname, "/");
317 strcat(inc_fullname, inc_filename);
319 inc_file = AllocateFile(inc_fullname, "r");
323 (errcode_for_file_access(),
324 errmsg("could not open secondary authentication file \"@%s\" as \"%s\": %m",
325 inc_filename, inc_fullname)));
328 /* return empty string, it matches nothing */
333 /* There is possible recursion here if the file contains @ */
334 tokenize_file(inc_file, &inc_lines, &inc_line_nums);
337 /* Create comma-separate string from List */
338 foreach(line, inc_lines)
340 List *token_list = (List *) lfirst(line);
343 foreach(token, token_list)
345 if (strlen(comma_str))
347 comma_str = repalloc(comma_str, strlen(comma_str) + 1);
348 strcat(comma_str, MULTI_VALUE_SEP);
350 comma_str = repalloc(comma_str,
351 strlen(comma_str) + strlen(lfirst(token)) + 1);
352 strcat(comma_str, lfirst(token));
356 free_lines(&inc_lines, &inc_line_nums);
363 * Tokenize the given file, storing the resulting data into two lists:
364 * a list of sublists, each sublist containing the tokens in a line of
365 * the file, and a list of line numbers.
368 tokenize_file(FILE *file, List **lines, List **line_nums)
370 List *current_line = NIL;
374 *lines = *line_nums = NIL;
378 buf = next_token_expand(file);
380 /* add token to list, unless we are at EOL or comment start */
383 if (current_line == NIL)
385 /* make a new line List, record its line number */
386 current_line = lappend(current_line, buf);
387 *lines = lappend(*lines, current_line);
388 *line_nums = lappend_int(*line_nums, line_number);
392 /* append token to current line's list */
393 current_line = lappend(current_line, buf);
398 /* we are at real or logical EOL, so force a new line List */
400 /* Advance line number whenever we reach EOL */
408 * Compare two lines based on their user/group names.
410 * Used for qsort() sorting.
413 user_group_qsort_cmp(const void *list1, const void *list2)
415 char *user1 = linitial(*(List **) list1);
416 char *user2 = linitial(*(List **) list2);
418 return strcmp(user1, user2);
423 * Compare two lines based on their user/group names.
425 * Used for bsearch() lookup.
428 user_group_bsearch_cmp(const void *user, const void *list)
430 char *user2 = linitial(*(List **) list);
432 return strcmp(user, user2);
437 * Lookup a group name in the pg_group file
440 get_group_line(const char *group)
442 /* On some versions of Solaris, bsearch of zero items dumps core */
443 if (group_length == 0)
446 return (List **) bsearch((void *) group,
447 (void *) group_sorted,
450 user_group_bsearch_cmp);
455 * Lookup a user name in the pg_shadow file
458 get_user_line(const char *user)
460 /* On some versions of Solaris, bsearch of zero items dumps core */
461 if (user_length == 0)
464 return (List **) bsearch((void *) user,
465 (void *) user_sorted,
468 user_group_bsearch_cmp);
473 * Check group for a specific user.
476 check_group(char *group, char *user)
480 if ((line = get_group_line(group)) != NULL)
484 /* skip over the group name */
485 for_each_cell(line_item, lnext(list_head(*line)))
487 if (strcmp(lfirst(line_item), user) == 0)
496 * Check comma user list for a specific user, handle group names.
499 check_user(char *user, char *param_str)
503 for (tok = strtok(param_str, MULTI_VALUE_SEP); tok != NULL; tok = strtok(NULL, MULTI_VALUE_SEP))
507 if (check_group(tok + 1, user))
510 else if (strcmp(tok, user) == 0 ||
511 strcmp(tok, "all\n") == 0)
519 * Check to see if db/user combination matches param string.
522 check_db(char *dbname, char *user, char *param_str)
526 for (tok = strtok(param_str, MULTI_VALUE_SEP); tok != NULL; tok = strtok(NULL, MULTI_VALUE_SEP))
528 if (strcmp(tok, "all\n") == 0)
530 else if (strcmp(tok, "sameuser\n") == 0)
532 if (strcmp(dbname, user) == 0)
535 else if (strcmp(tok, "samegroup\n") == 0)
537 if (check_group(dbname, user))
540 else if (strcmp(tok, dbname) == 0)
548 * Scan the rest of a host record (after the mask field)
549 * and return the interpretation of it as *userauth_p, *auth_arg_p, and
550 * *error_p. *line_item points to the next token of the line, and is
551 * advanced over successfully-read tokens.
554 parse_hba_auth(ListCell **line_item, UserAuth *userauth_p,
555 char **auth_arg_p, bool *error_p)
567 token = lfirst(*line_item);
568 if (strcmp(token, "trust") == 0)
569 *userauth_p = uaTrust;
570 else if (strcmp(token, "ident") == 0)
571 *userauth_p = uaIdent;
572 else if (strcmp(token, "password") == 0)
573 *userauth_p = uaPassword;
574 else if (strcmp(token, "krb4") == 0)
575 *userauth_p = uaKrb4;
576 else if (strcmp(token, "krb5") == 0)
577 *userauth_p = uaKrb5;
578 else if (strcmp(token, "reject") == 0)
579 *userauth_p = uaReject;
580 else if (strcmp(token, "md5") == 0)
582 else if (strcmp(token, "crypt") == 0)
583 *userauth_p = uaCrypt;
585 else if (strcmp(token, "pam") == 0)
593 *line_item = lnext(*line_item);
595 /* Get the authentication argument token, if any */
598 token = lfirst(*line_item);
599 *auth_arg_p = pstrdup(token);
600 *line_item = lnext(*line_item);
601 /* If there is more on the line, it is an error */
609 * Process one line from the hba config file.
611 * See if it applies to a connection from a host with IP address port->raddr
612 * to a database named port->database. If so, return *found_p true
613 * and fill in the auth arguments into the appropriate port fields.
614 * If not, leave *found_p as it was. If the record has a syntax error,
615 * return *error_p true, after issuing a message to the log. If no error,
616 * leave *error_p as it was.
619 parse_hba(List *line, int line_num, hbaPort *port,
620 bool *found_p, bool *error_p)
625 struct addrinfo *gai_result;
626 struct addrinfo hints;
628 struct sockaddr_storage addr;
629 struct sockaddr_storage mask;
633 line_item = list_head(line);
634 /* Check the record type. */
635 token = lfirst(line_item);
636 if (strcmp(token, "local") == 0)
638 /* Get the database. */
639 line_item = lnext(line_item);
642 db = lfirst(line_item);
645 line_item = lnext(line_item);
648 user = lfirst(line_item);
650 line_item = lnext(line_item);
654 /* Read the rest of the line. */
655 parse_hba_auth(&line_item, &port->auth_method,
656 &port->auth_arg, error_p);
660 /* Disallow auth methods that always need TCP/IP sockets to work */
661 if (port->auth_method == uaKrb4 ||
662 port->auth_method == uaKrb5)
665 /* Does not match if connection isn't AF_UNIX */
666 if (!IS_AF_UNIX(port->raddr.addr.ss_family))
669 else if (strcmp(token, "host") == 0
670 || strcmp(token, "hostssl") == 0
671 || strcmp(token, "hostnossl") == 0)
674 if (token[4] == 's') /* "hostssl" */
677 /* Record does not match if we are not on an SSL connection */
681 /* Placeholder to require specific SSL level, perhaps? */
682 /* Or a client certificate */
684 /* Since we were on SSL, proceed as with normal 'host' mode */
686 /* We don't accept this keyword at all if no SSL support */
691 else if (token[4] == 'n') /* "hostnossl" */
693 /* Record does not match if we are on an SSL connection */
699 /* Get the database. */
700 line_item = lnext(line_item);
703 db = lfirst(line_item);
706 line_item = lnext(line_item);
709 user = lfirst(line_item);
711 /* Read the IP address field. (with or without CIDR netmask) */
712 line_item = lnext(line_item);
715 token = lfirst(line_item);
717 /* Check if it has a CIDR suffix and if so isolate it */
718 cidr_slash = strchr(token, '/');
722 /* Get the IP address either way */
723 hints.ai_flags = AI_NUMERICHOST;
724 hints.ai_family = PF_UNSPEC;
725 hints.ai_socktype = 0;
726 hints.ai_protocol = 0;
727 hints.ai_addrlen = 0;
728 hints.ai_canonname = NULL;
729 hints.ai_addr = NULL;
730 hints.ai_next = NULL;
732 ret = getaddrinfo_all(token, NULL, &hints, &gai_result);
733 if (ret || !gai_result)
736 (errcode(ERRCODE_CONFIG_FILE_ERROR),
737 errmsg("invalid IP address \"%s\" in pg_hba.conf file line %d: %s",
738 token, line_num, gai_strerror(ret))));
742 freeaddrinfo_all(hints.ai_family, gai_result);
743 goto hba_other_error;
749 memcpy(&addr, gai_result->ai_addr, gai_result->ai_addrlen);
750 freeaddrinfo_all(hints.ai_family, gai_result);
752 /* Get the netmask */
755 if (SockAddr_cidr_mask(&mask, cidr_slash + 1, addr.ss_family) < 0)
760 /* Read the mask field. */
761 line_item = lnext(line_item);
764 token = lfirst(line_item);
766 ret = getaddrinfo_all(token, NULL, &hints, &gai_result);
767 if (ret || !gai_result)
770 (errcode(ERRCODE_CONFIG_FILE_ERROR),
771 errmsg("invalid IP mask \"%s\" in pg_hba.conf file line %d: %s",
772 token, line_num, gai_strerror(ret))));
774 freeaddrinfo_all(hints.ai_family, gai_result);
775 goto hba_other_error;
778 memcpy(&mask, gai_result->ai_addr, gai_result->ai_addrlen);
779 freeaddrinfo_all(hints.ai_family, gai_result);
781 if (addr.ss_family != mask.ss_family)
784 (errcode(ERRCODE_CONFIG_FILE_ERROR),
785 errmsg("IP address and mask do not match in pg_hba.conf file line %d",
787 goto hba_other_error;
791 if (addr.ss_family != port->raddr.addr.ss_family)
794 * Wrong address family. We allow only one case: if the
795 * file has IPv4 and the port is IPv6, promote the file
796 * address to IPv6 and try to match that way.
799 if (addr.ss_family == AF_INET &&
800 port->raddr.addr.ss_family == AF_INET6)
802 promote_v4_to_v6_addr(&addr);
803 promote_v4_to_v6_mask(&mask);
806 #endif /* HAVE_IPV6 */
808 /* Line doesn't match client port, so ignore it. */
813 /* Ignore line if client port is not in the matching addr range. */
814 if (!rangeSockAddr(&port->raddr.addr, &addr, &mask))
817 /* Read the rest of the line. */
818 line_item = lnext(line_item);
821 parse_hba_auth(&line_item, &port->auth_method,
822 &port->auth_arg, error_p);
829 /* Does the entry match database and user? */
830 if (!check_db(port->database_name, port->user_name, db))
832 if (!check_user(port->user_name, user))
842 (errcode(ERRCODE_CONFIG_FILE_ERROR),
843 errmsg("invalid entry in pg_hba.conf file at line %d, token \"%s\"",
844 line_num, (char *) lfirst(line_item))));
847 (errcode(ERRCODE_CONFIG_FILE_ERROR),
848 errmsg("missing field in pg_hba.conf file at end of line %d",
851 /* Come here if suitable message already logged */
858 * Scan the (pre-parsed) hba file line by line, looking for a match
859 * to the port's connection request.
862 check_hba(hbaPort *port)
864 bool found_entry = false;
869 forboth(line, hba_lines, line_num, hba_line_nums)
871 parse_hba(lfirst(line), lfirst_int(line_num),
872 port, &found_entry, &error);
873 if (found_entry || error)
879 /* If no matching entry was found, synthesize 'reject' entry. */
881 port->auth_method = uaReject;
891 * Open the group file if possible (return NULL if not)
899 filename = group_getfilename();
900 groupfile = AllocateFile(filename, "r");
902 if (groupfile == NULL && errno != ENOENT)
904 (errcode_for_file_access(),
905 errmsg("could not open file \"%s\": %m", filename)));
915 * Open the password file if possible (return NULL if not)
923 filename = user_getfilename();
924 pwdfile = AllocateFile(filename, "r");
926 if (pwdfile == NULL && errno != ENOENT)
928 (errcode_for_file_access(),
929 errmsg("could not open file \"%s\": %m", filename)));
939 * Load group/user name mapping file
946 /* Discard any old data */
947 if (group_lines || group_line_nums)
948 free_lines(&group_lines, &group_line_nums);
954 group_file = group_openfile();
957 tokenize_file(group_file, &group_lines, &group_line_nums);
958 FreeFile(group_file);
960 /* create sorted lines for binary searching */
961 group_length = list_length(group_lines);
967 group_sorted = palloc(group_length * sizeof(List *));
969 foreach(line, group_lines)
970 group_sorted[i++] = lfirst(line);
972 qsort((void *) group_sorted,
975 user_group_qsort_cmp);
981 * Load user/password mapping file
988 /* Discard any old data */
989 if (user_lines || user_line_nums)
990 free_lines(&user_lines, &user_line_nums);
996 user_file = user_openfile();
999 tokenize_file(user_file, &user_lines, &user_line_nums);
1000 FreeFile(user_file);
1002 /* create sorted lines for binary searching */
1003 user_length = list_length(user_lines);
1009 user_sorted = palloc(user_length * sizeof(List *));
1011 foreach(line, user_lines)
1012 user_sorted[i++] = lfirst(line);
1014 qsort((void *) user_sorted,
1017 user_group_qsort_cmp);
1023 * Read the config file and create a List of Lists of tokens in the file.
1024 * If we find a file by the old name of the config file (pg_hba), we issue
1025 * an error message because it probably needs to be converted. He didn't
1026 * follow directions and just installed his old hba file in the new database
1033 FILE *file; /* The config file we have to read */
1034 char *conf_file; /* The name of the config file */
1036 if (hba_lines || hba_line_nums)
1037 free_lines(&hba_lines, &hba_line_nums);
1039 /* Put together the full pathname to the config file. */
1040 bufsize = (strlen(DataDir) + strlen(CONF_FILE) + 2) * sizeof(char);
1041 conf_file = (char *) palloc(bufsize);
1042 snprintf(conf_file, bufsize, "%s/%s", DataDir, CONF_FILE);
1044 file = AllocateFile(conf_file, "r");
1047 (errcode_for_file_access(),
1048 errmsg("could not open configuration file \"%s\": %m",
1051 tokenize_file(file, &hba_lines, &hba_line_nums);
1058 * Process one line from the ident config file.
1060 * Take the line and compare it to the needed map, pg_user and ident_user.
1061 * *found_p and *error_p are set according to our results.
1064 parse_ident_usermap(List *line, int line_number, const char *usermap_name,
1065 const char *pg_user, const char *ident_user,
1066 bool *found_p, bool *error_p)
1068 ListCell *line_item;
1072 char *file_ident_user;
1077 Assert(line != NIL);
1078 line_item = list_head(line);
1080 /* Get the map token (must exist) */
1081 token = lfirst(line_item);
1084 /* Get the ident user token (must be provided) */
1085 line_item = lnext(line_item);
1088 token = lfirst(line_item);
1089 file_ident_user = token;
1091 /* Get the PG username token */
1092 line_item = lnext(line_item);
1095 token = lfirst(line_item);
1096 file_pguser = token;
1099 if (strcmp(file_map, usermap_name) == 0 &&
1100 strcmp(file_pguser, pg_user) == 0 &&
1101 strcmp(file_ident_user, ident_user) == 0)
1108 (errcode(ERRCODE_CONFIG_FILE_ERROR),
1109 errmsg("invalid entry in pg_ident.conf file at line %d, token \"%s\"",
1110 line_number, (const char *) lfirst(line_item))));
1113 (errcode(ERRCODE_CONFIG_FILE_ERROR),
1114 errmsg("missing entry in pg_ident.conf file at end of line %d",
1122 * Scan the (pre-parsed) ident usermap file line by line, looking for a match
1124 * See if the user with ident username "ident_user" is allowed to act
1125 * as Postgres user "pguser" according to usermap "usermap_name".
1127 * Special case: For usermap "sameuser", don't look in the usermap
1128 * file. That's an implied map where "pguser" must be identical to
1129 * "ident_user" in order to be authorized.
1131 * Iff authorized, return true.
1134 check_ident_usermap(const char *usermap_name,
1135 const char *pg_user,
1136 const char *ident_user)
1138 bool found_entry = false,
1141 if (usermap_name == NULL || usermap_name[0] == '\0')
1144 (errcode(ERRCODE_CONFIG_FILE_ERROR),
1145 errmsg("cannot use Ident authentication without usermap field")));
1146 found_entry = false;
1148 else if (strcmp(usermap_name, "sameuser\n") == 0)
1150 if (strcmp(pg_user, ident_user) == 0)
1153 found_entry = false;
1157 ListCell *line_cell, *num_cell;
1159 forboth(line_cell, ident_lines, num_cell, ident_line_nums)
1161 parse_ident_usermap(lfirst(line_cell), lfirst_int(num_cell),
1162 usermap_name, pg_user, ident_user,
1163 &found_entry, &error);
1164 if (found_entry || error)
1173 * Read the ident config file and create a List of Lists of tokens in the file.
1178 FILE *file; /* The map file we have to read */
1179 char *map_file; /* The name of the map file we have to
1183 if (ident_lines || ident_line_nums)
1184 free_lines(&ident_lines, &ident_line_nums);
1186 /* put together the full pathname to the map file */
1187 bufsize = (strlen(DataDir) + strlen(USERMAP_FILE) + 2) * sizeof(char);
1188 map_file = (char *) palloc(bufsize);
1189 snprintf(map_file, bufsize, "%s/%s", DataDir, USERMAP_FILE);
1191 file = AllocateFile(map_file, "r");
1195 (errcode_for_file_access(),
1196 errmsg("could not open Ident usermap file \"%s\": %m",
1201 tokenize_file(file, &ident_lines, &ident_line_nums);
1209 * Parse the string "*ident_response" as a response from a query to an Ident
1210 * server. If it's a normal response indicating a user name, return true
1211 * and store the user name at *ident_user. If it's anything else,
1215 interpret_ident_response(char *ident_response,
1218 char *cursor = ident_response; /* Cursor into
1219 * *ident_response */
1222 * Ident's response, in the telnet tradition, should end in crlf
1225 if (strlen(ident_response) < 2)
1227 else if (ident_response[strlen(ident_response) - 2] != '\r')
1231 while (*cursor != ':' && *cursor != '\r')
1232 cursor++; /* skip port field */
1238 /* We're positioned to colon before response type field */
1239 char response_type[80];
1240 int i; /* Index into *response_type */
1242 cursor++; /* Go over colon */
1243 while (pg_isblank(*cursor))
1244 cursor++; /* skip blanks */
1246 while (*cursor != ':' && *cursor != '\r' && !pg_isblank(*cursor) &&
1247 i < (int) (sizeof(response_type) - 1))
1248 response_type[i++] = *cursor++;
1249 response_type[i] = '\0';
1250 while (pg_isblank(*cursor))
1251 cursor++; /* skip blanks */
1252 if (strcmp(response_type, "USERID") != 0)
1257 * It's a USERID response. Good. "cursor" should be
1258 * pointing to the colon that precedes the operating
1265 cursor++; /* Go over colon */
1266 /* Skip over operating system field. */
1267 while (*cursor != ':' && *cursor != '\r')
1273 int i; /* Index into *ident_user */
1275 cursor++; /* Go over colon */
1276 while (pg_isblank(*cursor))
1277 cursor++; /* skip blanks */
1278 /* Rest of line is user name. Copy it over. */
1280 while (*cursor != '\r' && i < IDENT_USERNAME_MAX)
1281 ident_user[i++] = *cursor++;
1282 ident_user[i] = '\0';
1293 * Talk to the ident server on host "remote_ip_addr" and find out who
1294 * owns the tcp connection from his port "remote_port" to port
1295 * "local_port_addr" on host "local_ip_addr". Return the user name the
1296 * ident server gives as "*ident_user".
1298 * IP addresses and port numbers are in network byte order.
1300 * But iff we're unable to get the information from ident, return false.
1303 ident_inet(const SockAddr remote_addr,
1304 const SockAddr local_addr,
1307 int sock_fd, /* File descriptor for socket on which we
1309 rc; /* Return code from a locally called
1312 char remote_addr_s[NI_MAXHOST];
1313 char remote_port[NI_MAXSERV];
1314 char local_addr_s[NI_MAXHOST];
1315 char local_port[NI_MAXSERV];
1316 char ident_port[NI_MAXSERV];
1317 char ident_query[80];
1318 char ident_response[80 + IDENT_USERNAME_MAX];
1319 struct addrinfo *ident_serv = NULL,
1324 * Might look a little weird to first convert it to text and then back
1325 * to sockaddr, but it's protocol independent.
1327 getnameinfo_all(&remote_addr.addr, remote_addr.salen,
1328 remote_addr_s, sizeof(remote_addr_s),
1329 remote_port, sizeof(remote_port),
1330 NI_NUMERICHOST | NI_NUMERICSERV);
1331 getnameinfo_all(&local_addr.addr, local_addr.salen,
1332 local_addr_s, sizeof(local_addr_s),
1333 local_port, sizeof(local_port),
1334 NI_NUMERICHOST | NI_NUMERICSERV);
1336 snprintf(ident_port, sizeof(ident_port), "%d", IDENT_PORT);
1337 hints.ai_flags = AI_NUMERICHOST;
1338 hints.ai_family = remote_addr.addr.ss_family;
1339 hints.ai_socktype = SOCK_STREAM;
1340 hints.ai_protocol = 0;
1341 hints.ai_addrlen = 0;
1342 hints.ai_canonname = NULL;
1343 hints.ai_addr = NULL;
1344 hints.ai_next = NULL;
1345 rc = getaddrinfo_all(remote_addr_s, ident_port, &hints, &ident_serv);
1346 if (rc || !ident_serv) {
1348 freeaddrinfo_all(hints.ai_family, ident_serv);
1349 return false; /* we don't expect this to happen */
1352 hints.ai_flags = AI_NUMERICHOST;
1353 hints.ai_family = local_addr.addr.ss_family;
1354 hints.ai_socktype = SOCK_STREAM;
1355 hints.ai_protocol = 0;
1356 hints.ai_addrlen = 0;
1357 hints.ai_canonname = NULL;
1358 hints.ai_addr = NULL;
1359 hints.ai_next = NULL;
1360 rc = getaddrinfo_all(local_addr_s, NULL, &hints, &la);
1363 freeaddrinfo_all(hints.ai_family, la);
1364 return false; /* we don't expect this to happen */
1367 sock_fd = socket(ident_serv->ai_family, ident_serv->ai_socktype,
1368 ident_serv->ai_protocol);
1372 (errcode_for_socket_access(),
1373 errmsg("could not create socket for Ident connection: %m")));
1374 ident_return = false;
1375 goto ident_inet_done;
1379 * Bind to the address which the client originally contacted,
1380 * otherwise the ident server won't be able to match up the right
1381 * connection. This is necessary if the PostgreSQL server is running
1384 rc = bind(sock_fd, la->ai_addr, la->ai_addrlen);
1388 (errcode_for_socket_access(),
1389 errmsg("could not bind to local address \"%s\": %m",
1391 ident_return = false;
1392 goto ident_inet_done;
1395 rc = connect(sock_fd, ident_serv->ai_addr,
1396 ident_serv->ai_addrlen);
1400 (errcode_for_socket_access(),
1401 errmsg("could not connect to Ident server at address \"%s\", port %s: %m",
1402 remote_addr_s, ident_port)));
1403 ident_return = false;
1404 goto ident_inet_done;
1407 /* The query we send to the Ident server */
1408 snprintf(ident_query, sizeof(ident_query), "%s,%s\r\n",
1409 remote_port, local_port);
1411 /* loop in case send is interrupted */
1414 rc = send(sock_fd, ident_query, strlen(ident_query), 0);
1415 } while (rc < 0 && errno == EINTR);
1420 (errcode_for_socket_access(),
1421 errmsg("could not send query to Ident server at address \"%s\", port %s: %m",
1422 remote_addr_s, ident_port)));
1423 ident_return = false;
1424 goto ident_inet_done;
1429 rc = recv(sock_fd, ident_response, sizeof(ident_response) - 1, 0);
1430 } while (rc < 0 && errno == EINTR);
1435 (errcode_for_socket_access(),
1436 errmsg("could not receive response from Ident server at address \"%s\", port %s: %m",
1437 remote_addr_s, ident_port)));
1438 ident_return = false;
1439 goto ident_inet_done;
1442 ident_response[rc] = '\0';
1443 ident_return = interpret_ident_response(ident_response, ident_user);
1447 closesocket(sock_fd);
1448 freeaddrinfo_all(remote_addr.addr.ss_family, ident_serv);
1449 freeaddrinfo_all(local_addr.addr.ss_family, la);
1450 return ident_return;
1454 * Ask kernel about the credentials of the connecting process and
1455 * determine the symbolic name of the corresponding user.
1457 * Returns either true and the username put into "ident_user",
1458 * or false if we were unable to determine the username.
1460 #ifdef HAVE_UNIX_SOCKETS
1463 ident_unix(int sock, char *ident_user)
1465 #if defined(HAVE_GETPEEREID)
1466 /* OpenBSD style: */
1469 struct passwd *pass;
1472 if (getpeereid(sock, &uid, &gid) != 0)
1474 /* We didn't get a valid credentials struct. */
1476 (errcode_for_socket_access(),
1477 errmsg("could not get peer credentials: %m")));
1481 pass = getpwuid(uid);
1486 (errmsg("local user with ID %d does not exist",
1491 StrNCpy(ident_user, pass->pw_name, IDENT_USERNAME_MAX + 1);
1495 #elif defined(SO_PEERCRED)
1496 /* Linux style: use getsockopt(SO_PEERCRED) */
1497 struct ucred peercred;
1498 ACCEPT_TYPE_ARG3 so_len = sizeof(peercred);
1499 struct passwd *pass;
1502 if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) != 0 ||
1503 so_len != sizeof(peercred))
1505 /* We didn't get a valid credentials struct. */
1507 (errcode_for_socket_access(),
1508 errmsg("could not get peer credentials: %m")));
1512 pass = getpwuid(peercred.uid);
1517 (errmsg("local user with ID %d does not exist",
1518 (int) peercred.uid)));
1522 StrNCpy(ident_user, pass->pw_name, IDENT_USERNAME_MAX + 1);
1526 #elif defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || (defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS))
1529 /* Credentials structure */
1530 #if defined(HAVE_STRUCT_CMSGCRED)
1531 typedef struct cmsgcred Cred;
1533 #define cruid cmcred_uid
1534 #elif defined(HAVE_STRUCT_FCRED)
1535 typedef struct fcred Cred;
1537 #define cruid fc_uid
1538 #elif defined(HAVE_STRUCT_SOCKCRED)
1539 typedef struct sockcred Cred;
1541 #define cruid sc_uid
1545 /* Compute size without padding */
1546 char cmsgmem[ALIGN(sizeof(struct cmsghdr)) + ALIGN(sizeof(Cred))]; /* for NetBSD */
1548 /* Point to start of first structure */
1549 struct cmsghdr *cmsg = (struct cmsghdr *) cmsgmem;
1555 memset(&msg, 0, sizeof(msg));
1558 msg.msg_control = (char *) cmsg;
1559 msg.msg_controllen = sizeof(cmsgmem);
1560 memset(cmsg, 0, sizeof(cmsgmem));
1563 * The one character which is received here is not meaningful; its
1564 * purposes is only to make sure that recvmsg() blocks long enough for
1565 * the other side to send its credentials.
1567 iov.iov_base = &buf;
1570 if (recvmsg(sock, &msg, 0) < 0 ||
1571 cmsg->cmsg_len < sizeof(cmsgmem) ||
1572 cmsg->cmsg_type != SCM_CREDS)
1575 (errcode_for_socket_access(),
1576 errmsg("could not get peer credentials: %m")));
1580 cred = (Cred *) CMSG_DATA(cmsg);
1582 pw = getpwuid(cred->cruid);
1587 (errmsg("local user with ID %d does not exist",
1588 (int) cred->cruid)));
1592 StrNCpy(ident_user, pw->pw_name, IDENT_USERNAME_MAX + 1);
1598 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1599 errmsg("Ident authentication is not supported on local connections on this platform")));
1604 #endif /* HAVE_UNIX_SOCKETS */
1608 * Determine the username of the initiator of the connection described
1609 * by "port". Then look in the usermap file under the usermap
1610 * port->auth_arg and see if that user is equivalent to Postgres user
1613 * Return STATUS_OK if yes, STATUS_ERROR if no match (or couldn't get info).
1616 authident(hbaPort *port)
1618 char ident_user[IDENT_USERNAME_MAX + 1];
1620 switch (port->raddr.addr.ss_family)
1626 if (!ident_inet(port->raddr, port->laddr, ident_user))
1627 return STATUS_ERROR;
1630 #ifdef HAVE_UNIX_SOCKETS
1632 if (!ident_unix(port->sock, ident_user))
1633 return STATUS_ERROR;
1638 return STATUS_ERROR;
1641 if (check_ident_usermap(port->auth_arg, port->user_name, ident_user))
1644 return STATUS_ERROR;
1649 * Determine what authentication method should be used when accessing database
1650 * "database" from frontend "raddr", user "user". Return the method and
1651 * an optional argument (stored in fields of *port), and STATUS_OK.
1653 * Note that STATUS_ERROR indicates a problem with the hba config file.
1654 * If the file is OK but does not contain any entry matching the request,
1655 * we return STATUS_OK and method = uaReject.
1658 hba_getauthmethod(hbaPort *port)
1660 if (check_hba(port))
1663 return STATUS_ERROR;