PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
auth.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * auth.c
4  * Routines to handle network authentication
5  *
6  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/libpq/auth.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 
16 #include "postgres.h"
17 
18 #include <sys/param.h>
19 #include <sys/socket.h>
20 #include <netinet/in.h>
21 #include <arpa/inet.h>
22 #include <unistd.h>
23 #ifdef HAVE_SYS_SELECT_H
24 #include <sys/select.h>
25 #endif
26 
27 #include "commands/user.h"
28 #include "common/ip.h"
29 #include "common/md5.h"
30 #include "libpq/auth.h"
31 #include "libpq/crypt.h"
32 #include "libpq/libpq.h"
33 #include "libpq/pqformat.h"
34 #include "libpq/scram.h"
35 #include "miscadmin.h"
36 #include "replication/walsender.h"
37 #include "storage/ipc.h"
38 #include "utils/backend_random.h"
39 #include "utils/timestamp.h"
40 
41 
42 /*----------------------------------------------------------------
43  * Global authentication functions
44  *----------------------------------------------------------------
45  */
46 static void sendAuthRequest(Port *port, AuthRequest areq, char *extradata,
47  int extralen);
48 static void auth_failed(Port *port, int status, char *logdetail);
49 static char *recv_password_packet(Port *port);
50 
51 
52 /*----------------------------------------------------------------
53  * Password-based authentication methods (password, md5, and scram)
54  *----------------------------------------------------------------
55  */
56 static int CheckPasswordAuth(Port *port, char **logdetail);
57 static int CheckPWChallengeAuth(Port *port, char **logdetail);
58 
59 static int CheckMD5Auth(Port *port, char *shadow_pass, char **logdetail);
60 static int CheckSCRAMAuth(Port *port, char *shadow_pass, char **logdetail);
61 
62 
63 /*----------------------------------------------------------------
64  * Ident authentication
65  *----------------------------------------------------------------
66  */
67 /* Max size of username ident server can return */
68 #define IDENT_USERNAME_MAX 512
69 
70 /* Standard TCP port number for Ident service. Assigned by IANA */
71 #define IDENT_PORT 113
72 
73 static int ident_inet(hbaPort *port);
74 
75 #ifdef HAVE_UNIX_SOCKETS
76 static int auth_peer(hbaPort *port);
77 #endif
78 
79 
80 /*----------------------------------------------------------------
81  * PAM authentication
82  *----------------------------------------------------------------
83  */
84 #ifdef USE_PAM
85 #ifdef HAVE_PAM_PAM_APPL_H
86 #include <pam/pam_appl.h>
87 #endif
88 #ifdef HAVE_SECURITY_PAM_APPL_H
89 #include <security/pam_appl.h>
90 #endif
91 
92 #define PGSQL_PAM_SERVICE "postgresql" /* Service name passed to PAM */
93 
94 static int CheckPAMAuth(Port *port, char *user, char *password);
95 static int pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg,
96  struct pam_response ** resp, void *appdata_ptr);
97 
98 static struct pam_conv pam_passw_conv = {
99  &pam_passwd_conv_proc,
100  NULL
101 };
102 
103 static char *pam_passwd = NULL; /* Workaround for Solaris 2.6 brokenness */
104 static Port *pam_port_cludge; /* Workaround for passing "Port *port" into
105  * pam_passwd_conv_proc */
106 #endif /* USE_PAM */
107 
108 
109 /*----------------------------------------------------------------
110  * BSD authentication
111  *----------------------------------------------------------------
112  */
113 #ifdef USE_BSD_AUTH
114 #include <bsd_auth.h>
115 
116 static int CheckBSDAuth(Port *port, char *user);
117 #endif /* USE_BSD_AUTH */
118 
119 
120 /*----------------------------------------------------------------
121  * LDAP authentication
122  *----------------------------------------------------------------
123  */
124 #ifdef USE_LDAP
125 #ifndef WIN32
126 /* We use a deprecated function to keep the codepath the same as win32. */
127 #define LDAP_DEPRECATED 1
128 #include <ldap.h>
129 #else
130 #include <winldap.h>
131 
132 /* Correct header from the Platform SDK */
133 typedef
134 ULONG (*__ldap_start_tls_sA) (
135  IN PLDAP ExternalHandle,
136  OUT PULONG ServerReturnValue,
137  OUT LDAPMessage **result,
138  IN PLDAPControlA * ServerControls,
139  IN PLDAPControlA * ClientControls
140 );
141 #endif
142 
143 static int CheckLDAPAuth(Port *port);
144 #endif /* USE_LDAP */
145 
146 /*----------------------------------------------------------------
147  * Cert authentication
148  *----------------------------------------------------------------
149  */
150 #ifdef USE_SSL
151 static int CheckCertAuth(Port *port);
152 #endif
153 
154 
155 /*----------------------------------------------------------------
156  * Kerberos and GSSAPI GUCs
157  *----------------------------------------------------------------
158  */
161 
162 
163 /*----------------------------------------------------------------
164  * GSSAPI Authentication
165  *----------------------------------------------------------------
166  */
167 #ifdef ENABLE_GSS
168 #if defined(HAVE_GSSAPI_H)
169 #include <gssapi.h>
170 #else
171 #include <gssapi/gssapi.h>
172 #endif
173 
174 static int pg_GSS_recvauth(Port *port);
175 #endif /* ENABLE_GSS */
176 
177 
178 /*----------------------------------------------------------------
179  * SSPI Authentication
180  *----------------------------------------------------------------
181  */
182 #ifdef ENABLE_SSPI
183 typedef SECURITY_STATUS
184  (WINAPI * QUERY_SECURITY_CONTEXT_TOKEN_FN) (
185  PCtxtHandle, void **);
186 static int pg_SSPI_recvauth(Port *port);
187 static int pg_SSPI_make_upn(char *accountname,
188  size_t accountnamesize,
189  char *domainname,
190  size_t domainnamesize,
191  bool update_accountname);
192 #endif
193 
194 /*----------------------------------------------------------------
195  * RADIUS Authentication
196  *----------------------------------------------------------------
197  */
198 static int CheckRADIUSAuth(Port *port);
199 static int PerformRadiusTransaction(char *server, char *secret, char *portstr, char *identifier, char *user_name, char *passwd);
200 
201 
202 /*
203  * Maximum accepted size of GSS and SSPI authentication tokens.
204  *
205  * Kerberos tickets are usually quite small, but the TGTs issued by Windows
206  * domain controllers include an authorization field known as the Privilege
207  * Attribute Certificate (PAC), which contains the user's Windows permissions
208  * (group memberships etc.). The PAC is copied into all tickets obtained on
209  * the basis of this TGT (even those issued by Unix realms which the Windows
210  * realm trusts), and can be several kB in size. The maximum token size
211  * accepted by Windows systems is determined by the MaxAuthToken Windows
212  * registry setting. Microsoft recommends that it is not set higher than
213  * 65535 bytes, so that seems like a reasonable limit for us as well.
214  */
215 #define PG_MAX_AUTH_TOKEN_LENGTH 65535
216 
217 /*
218  * Maximum accepted size of SASL messages.
219  *
220  * The messages that the server or libpq generate are much smaller than this,
221  * but have some headroom.
222  */
223 #define PG_MAX_SASL_MESSAGE_LENGTH 1024
224 
225 /*----------------------------------------------------------------
226  * Global authentication functions
227  *----------------------------------------------------------------
228  */
229 
230 /*
231  * This hook allows plugins to get control following client authentication,
232  * but before the user has been informed about the results. It could be used
233  * to record login events, insert a delay after failed authentication, etc.
234  */
236 
237 /*
238  * Tell the user the authentication failed, but not (much about) why.
239  *
240  * There is a tradeoff here between security concerns and making life
241  * unnecessarily difficult for legitimate users. We would not, for example,
242  * want to report the password we were expecting to receive...
243  * But it seems useful to report the username and authorization method
244  * in use, and these are items that must be presumed known to an attacker
245  * anyway.
246  * Note that many sorts of failure report additional information in the
247  * postmaster log, which we hope is only readable by good guys. In
248  * particular, if logdetail isn't NULL, we send that string to the log.
249  */
250 static void
251 auth_failed(Port *port, int status, char *logdetail)
252 {
253  const char *errstr;
254  char *cdetail;
255  int errcode_return = ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION;
256 
257  /*
258  * If we failed due to EOF from client, just quit; there's no point in
259  * trying to send a message to the client, and not much point in logging
260  * the failure in the postmaster log. (Logging the failure might be
261  * desirable, were it not for the fact that libpq closes the connection
262  * unceremoniously if challenged for a password when it hasn't got one to
263  * send. We'll get a useless log entry for every psql connection under
264  * password auth, even if it's perfectly successful, if we log STATUS_EOF
265  * events.)
266  */
267  if (status == STATUS_EOF)
268  proc_exit(0);
269 
270  switch (port->hba->auth_method)
271  {
272  case uaReject:
273  case uaImplicitReject:
274  errstr = gettext_noop("authentication failed for user \"%s\": host rejected");
275  break;
276  case uaTrust:
277  errstr = gettext_noop("\"trust\" authentication failed for user \"%s\"");
278  break;
279  case uaIdent:
280  errstr = gettext_noop("Ident authentication failed for user \"%s\"");
281  break;
282  case uaPeer:
283  errstr = gettext_noop("Peer authentication failed for user \"%s\"");
284  break;
285  case uaPassword:
286  case uaMD5:
287  case uaSCRAM:
288  errstr = gettext_noop("password authentication failed for user \"%s\"");
289  /* We use it to indicate if a .pgpass password failed. */
290  errcode_return = ERRCODE_INVALID_PASSWORD;
291  break;
292  case uaGSS:
293  errstr = gettext_noop("GSSAPI authentication failed for user \"%s\"");
294  break;
295  case uaSSPI:
296  errstr = gettext_noop("SSPI authentication failed for user \"%s\"");
297  break;
298  case uaPAM:
299  errstr = gettext_noop("PAM authentication failed for user \"%s\"");
300  break;
301  case uaBSD:
302  errstr = gettext_noop("BSD authentication failed for user \"%s\"");
303  break;
304  case uaLDAP:
305  errstr = gettext_noop("LDAP authentication failed for user \"%s\"");
306  break;
307  case uaCert:
308  errstr = gettext_noop("certificate authentication failed for user \"%s\"");
309  break;
310  case uaRADIUS:
311  errstr = gettext_noop("RADIUS authentication failed for user \"%s\"");
312  break;
313  default:
314  errstr = gettext_noop("authentication failed for user \"%s\": invalid authentication method");
315  break;
316  }
317 
318  cdetail = psprintf(_("Connection matched pg_hba.conf line %d: \"%s\""),
319  port->hba->linenumber, port->hba->rawline);
320  if (logdetail)
321  logdetail = psprintf("%s\n%s", logdetail, cdetail);
322  else
323  logdetail = cdetail;
324 
325  ereport(FATAL,
326  (errcode(errcode_return),
327  errmsg(errstr, port->user_name),
328  logdetail ? errdetail_log("%s", logdetail) : 0));
329 
330  /* doesn't return */
331 }
332 
333 
334 /*
335  * Client authentication starts here. If there is an error, this
336  * function does not return and the backend process is terminated.
337  */
338 void
340 {
341  int status = STATUS_ERROR;
342  char *logdetail = NULL;
343 
344  /*
345  * Get the authentication method to use for this frontend/database
346  * combination. Note: we do not parse the file at this point; this has
347  * already been done elsewhere. hba.c dropped an error message into the
348  * server logfile if parsing the hba config file failed.
349  */
350  hba_getauthmethod(port);
351 
353 
354  /*
355  * This is the first point where we have access to the hba record for the
356  * current connection, so perform any verifications based on the hba
357  * options field that should be done *before* the authentication here.
358  */
359  if (port->hba->clientcert)
360  {
361  /* If we haven't loaded a root certificate store, fail */
363  ereport(FATAL,
364  (errcode(ERRCODE_CONFIG_FILE_ERROR),
365  errmsg("client certificates can only be checked if a root certificate store is available")));
366 
367  /*
368  * If we loaded a root certificate store, and if a certificate is
369  * present on the client, then it has been verified against our root
370  * certificate store, and the connection would have been aborted
371  * already if it didn't verify ok.
372  */
373  if (!port->peer_cert_valid)
374  ereport(FATAL,
375  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
376  errmsg("connection requires a valid client certificate")));
377  }
378 
379  /*
380  * Now proceed to do the actual authentication check
381  */
382  switch (port->hba->auth_method)
383  {
384  case uaReject:
385 
386  /*
387  * An explicit "reject" entry in pg_hba.conf. This report exposes
388  * the fact that there's an explicit reject entry, which is
389  * perhaps not so desirable from a security standpoint; but the
390  * message for an implicit reject could confuse the DBA a lot when
391  * the true situation is a match to an explicit reject. And we
392  * don't want to change the message for an implicit reject. As
393  * noted below, the additional information shown here doesn't
394  * expose anything not known to an attacker.
395  */
396  {
397  char hostinfo[NI_MAXHOST];
398 
399  pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
400  hostinfo, sizeof(hostinfo),
401  NULL, 0,
403 
404  if (am_walsender)
405  {
406 #ifdef USE_SSL
407  ereport(FATAL,
408  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
409  errmsg("pg_hba.conf rejects replication connection for host \"%s\", user \"%s\", %s",
410  hostinfo, port->user_name,
411  port->ssl_in_use ? _("SSL on") : _("SSL off"))));
412 #else
413  ereport(FATAL,
414  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
415  errmsg("pg_hba.conf rejects replication connection for host \"%s\", user \"%s\"",
416  hostinfo, port->user_name)));
417 #endif
418  }
419  else
420  {
421 #ifdef USE_SSL
422  ereport(FATAL,
423  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
424  errmsg("pg_hba.conf rejects connection for host \"%s\", user \"%s\", database \"%s\", %s",
425  hostinfo, port->user_name,
426  port->database_name,
427  port->ssl_in_use ? _("SSL on") : _("SSL off"))));
428 #else
429  ereport(FATAL,
430  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
431  errmsg("pg_hba.conf rejects connection for host \"%s\", user \"%s\", database \"%s\"",
432  hostinfo, port->user_name,
433  port->database_name)));
434 #endif
435  }
436  break;
437  }
438 
439  case uaImplicitReject:
440 
441  /*
442  * No matching entry, so tell the user we fell through.
443  *
444  * NOTE: the extra info reported here is not a security breach,
445  * because all that info is known at the frontend and must be
446  * assumed known to bad guys. We're merely helping out the less
447  * clueful good guys.
448  */
449  {
450  char hostinfo[NI_MAXHOST];
451 
452  pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
453  hostinfo, sizeof(hostinfo),
454  NULL, 0,
456 
457 #define HOSTNAME_LOOKUP_DETAIL(port) \
458  (port->remote_hostname ? \
459  (port->remote_hostname_resolv == +1 ? \
460  errdetail_log("Client IP address resolved to \"%s\", forward lookup matches.", \
461  port->remote_hostname) : \
462  port->remote_hostname_resolv == 0 ? \
463  errdetail_log("Client IP address resolved to \"%s\", forward lookup not checked.", \
464  port->remote_hostname) : \
465  port->remote_hostname_resolv == -1 ? \
466  errdetail_log("Client IP address resolved to \"%s\", forward lookup does not match.", \
467  port->remote_hostname) : \
468  port->remote_hostname_resolv == -2 ? \
469  errdetail_log("Could not translate client host name \"%s\" to IP address: %s.", \
470  port->remote_hostname, \
471  gai_strerror(port->remote_hostname_errcode)) : \
472  0) \
473  : (port->remote_hostname_resolv == -2 ? \
474  errdetail_log("Could not resolve client IP address to a host name: %s.", \
475  gai_strerror(port->remote_hostname_errcode)) : \
476  0))
477 
478  if (am_walsender)
479  {
480 #ifdef USE_SSL
481  ereport(FATAL,
482  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
483  errmsg("no pg_hba.conf entry for replication connection from host \"%s\", user \"%s\", %s",
484  hostinfo, port->user_name,
485  port->ssl_in_use ? _("SSL on") : _("SSL off")),
486  HOSTNAME_LOOKUP_DETAIL(port)));
487 #else
488  ereport(FATAL,
489  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
490  errmsg("no pg_hba.conf entry for replication connection from host \"%s\", user \"%s\"",
491  hostinfo, port->user_name),
492  HOSTNAME_LOOKUP_DETAIL(port)));
493 #endif
494  }
495  else
496  {
497 #ifdef USE_SSL
498  ereport(FATAL,
499  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
500  errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\", %s",
501  hostinfo, port->user_name,
502  port->database_name,
503  port->ssl_in_use ? _("SSL on") : _("SSL off")),
504  HOSTNAME_LOOKUP_DETAIL(port)));
505 #else
506  ereport(FATAL,
507  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
508  errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\"",
509  hostinfo, port->user_name,
510  port->database_name),
511  HOSTNAME_LOOKUP_DETAIL(port)));
512 #endif
513  }
514  break;
515  }
516 
517  case uaGSS:
518 #ifdef ENABLE_GSS
519  sendAuthRequest(port, AUTH_REQ_GSS, NULL, 0);
520  status = pg_GSS_recvauth(port);
521 #else
522  Assert(false);
523 #endif
524  break;
525 
526  case uaSSPI:
527 #ifdef ENABLE_SSPI
529  status = pg_SSPI_recvauth(port);
530 #else
531  Assert(false);
532 #endif
533  break;
534 
535  case uaPeer:
536 #ifdef HAVE_UNIX_SOCKETS
537  status = auth_peer(port);
538 #else
539  Assert(false);
540 #endif
541  break;
542 
543  case uaIdent:
544  status = ident_inet(port);
545  break;
546 
547  case uaMD5:
548  case uaSCRAM:
549  status = CheckPWChallengeAuth(port, &logdetail);
550  break;
551 
552  case uaPassword:
553  status = CheckPasswordAuth(port, &logdetail);
554  break;
555 
556  case uaPAM:
557 #ifdef USE_PAM
558  status = CheckPAMAuth(port, port->user_name, "");
559 #else
560  Assert(false);
561 #endif /* USE_PAM */
562  break;
563 
564  case uaBSD:
565 #ifdef USE_BSD_AUTH
566  status = CheckBSDAuth(port, port->user_name);
567 #else
568  Assert(false);
569 #endif /* USE_BSD_AUTH */
570  break;
571 
572  case uaLDAP:
573 #ifdef USE_LDAP
574  status = CheckLDAPAuth(port);
575 #else
576  Assert(false);
577 #endif
578  break;
579 
580  case uaCert:
581 #ifdef USE_SSL
582  status = CheckCertAuth(port);
583 #else
584  Assert(false);
585 #endif
586  break;
587  case uaRADIUS:
588  status = CheckRADIUSAuth(port);
589  break;
590  case uaTrust:
591  status = STATUS_OK;
592  break;
593  }
594 
596  (*ClientAuthentication_hook) (port, status);
597 
598  if (status == STATUS_OK)
599  sendAuthRequest(port, AUTH_REQ_OK, NULL, 0);
600  else
601  auth_failed(port, status, logdetail);
602 }
603 
604 
605 /*
606  * Send an authentication request packet to the frontend.
607  */
608 static void
609 sendAuthRequest(Port *port, AuthRequest areq, char *extradata, int extralen)
610 {
612 
614 
615  pq_beginmessage(&buf, 'R');
616  pq_sendint(&buf, (int32) areq, sizeof(int32));
617  if (extralen > 0)
618  pq_sendbytes(&buf, extradata, extralen);
619 
620  pq_endmessage(&buf);
621 
622  /*
623  * Flush message so client will see it, except for AUTH_REQ_OK, which need
624  * not be sent until we are ready for queries.
625  */
626  if (areq != AUTH_REQ_OK)
627  pq_flush();
628 
630 }
631 
632 /*
633  * Collect password response packet from frontend.
634  *
635  * Returns NULL if couldn't get password, else palloc'd string.
636  */
637 static char *
639 {
641 
642  pq_startmsgread();
643  if (PG_PROTOCOL_MAJOR(port->proto) >= 3)
644  {
645  /* Expect 'p' message type */
646  int mtype;
647 
648  mtype = pq_getbyte();
649  if (mtype != 'p')
650  {
651  /*
652  * If the client just disconnects without offering a password,
653  * don't make a log entry. This is legal per protocol spec and in
654  * fact commonly done by psql, so complaining just clutters the
655  * log.
656  */
657  if (mtype != EOF)
659  (errcode(ERRCODE_PROTOCOL_VIOLATION),
660  errmsg("expected password response, got message type %d",
661  mtype)));
662  return NULL; /* EOF or bad message type */
663  }
664  }
665  else
666  {
667  /* For pre-3.0 clients, avoid log entry if they just disconnect */
668  if (pq_peekbyte() == EOF)
669  return NULL; /* EOF */
670  }
671 
672  initStringInfo(&buf);
673  if (pq_getmessage(&buf, 1000)) /* receive password */
674  {
675  /* EOF - pq_getmessage already logged a suitable message */
676  pfree(buf.data);
677  return NULL;
678  }
679 
680  /*
681  * Apply sanity check: password packet length should agree with length of
682  * contained string. Note it is safe to use strlen here because
683  * StringInfo is guaranteed to have an appended '\0'.
684  */
685  if (strlen(buf.data) + 1 != buf.len)
687  (errcode(ERRCODE_PROTOCOL_VIOLATION),
688  errmsg("invalid password packet size")));
689 
690  /* Do not echo password to logs, for security. */
691  elog(DEBUG5, "received password packet");
692 
693  /*
694  * Return the received string. Note we do not attempt to do any
695  * character-set conversion on it; since we don't yet know the client's
696  * encoding, there wouldn't be much point.
697  */
698  return buf.data;
699 }
700 
701 
702 /*----------------------------------------------------------------
703  * Password-based authentication mechanisms
704  *----------------------------------------------------------------
705  */
706 
707 /*
708  * Plaintext password authentication.
709  */
710 static int
711 CheckPasswordAuth(Port *port, char **logdetail)
712 {
713  char *passwd;
714  int result;
715  char *shadow_pass;
716 
718 
719  passwd = recv_password_packet(port);
720  if (passwd == NULL)
721  return STATUS_EOF; /* client wouldn't send password */
722 
723  shadow_pass = get_role_password(port->user_name, logdetail);
724  if (shadow_pass)
725  {
726  result = plain_crypt_verify(port->user_name, shadow_pass, passwd,
727  logdetail);
728  }
729  else
730  result = STATUS_ERROR;
731 
732  if (shadow_pass)
733  pfree(shadow_pass);
734  pfree(passwd);
735 
736  return result;
737 }
738 
739 /*
740  * MD5 and SCRAM authentication.
741  */
742 static int
743 CheckPWChallengeAuth(Port *port, char **logdetail)
744 {
745  int auth_result;
746  char *shadow_pass;
747  PasswordType pwtype;
748 
749  Assert(port->hba->auth_method == uaSCRAM ||
750  port->hba->auth_method == uaMD5);
751 
752  /* First look up the user's password. */
753  shadow_pass = get_role_password(port->user_name, logdetail);
754 
755  /*
756  * If the user does not exist, or has no password, we still go through the
757  * motions of authentication, to avoid revealing to the client that the
758  * user didn't exist. If 'md5' is allowed, we choose whether to use 'md5'
759  * or 'scram' authentication based on current password_encryption setting.
760  * The idea is that most genuine users probably have a password of that
761  * type, if we pretend that this user had a password of that type, too, it
762  * "blends in" best.
763  *
764  * If the user had a password, but it was expired, we'll use the details
765  * of the expired password for the authentication, but report it as
766  * failure to the client even if correct password was given.
767  */
768  if (!shadow_pass)
769  pwtype = Password_encryption;
770  else
771  pwtype = get_password_type(shadow_pass);
772 
773  /*
774  * If 'md5' authentication is allowed, decide whether to perform 'md5' or
775  * 'scram' authentication based on the type of password the user has. If
776  * it's an MD5 hash, we must do MD5 authentication, and if it's a SCRAM
777  * verifier, we must do SCRAM authentication. If it's stored in
778  * plaintext, we could do either one, so we opt for the more secure
779  * mechanism, SCRAM.
780  *
781  * If MD5 authentication is not allowed, always use SCRAM. If the user
782  * had an MD5 password, CheckSCRAMAuth() will fail.
783  */
784  if (port->hba->auth_method == uaMD5 && pwtype == PASSWORD_TYPE_MD5)
785  {
786  auth_result = CheckMD5Auth(port, shadow_pass, logdetail);
787  }
788  else
789  {
790  auth_result = CheckSCRAMAuth(port, shadow_pass, logdetail);
791  }
792 
793  if (shadow_pass)
794  pfree(shadow_pass);
795 
796  /*
797  * If get_role_password() returned error, return error, even if the
798  * authentication succeeded.
799  */
800  if (!shadow_pass)
801  {
802  Assert(auth_result != STATUS_OK);
803  return STATUS_ERROR;
804  }
805  return auth_result;
806 }
807 
808 static int
809 CheckMD5Auth(Port *port, char *shadow_pass, char **logdetail)
810 {
811  char md5Salt[4]; /* Password salt */
812  char *passwd;
813  int result;
814 
815  if (Db_user_namespace)
816  ereport(FATAL,
817  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
818  errmsg("MD5 authentication is not supported when \"db_user_namespace\" is enabled")));
819 
820  /* include the salt to use for computing the response */
821  if (!pg_backend_random(md5Salt, 4))
822  {
823  ereport(LOG,
824  (errmsg("could not generate random MD5 salt")));
825  return STATUS_ERROR;
826  }
827 
828  sendAuthRequest(port, AUTH_REQ_MD5, md5Salt, 4);
829 
830  passwd = recv_password_packet(port);
831  if (passwd == NULL)
832  return STATUS_EOF; /* client wouldn't send password */
833 
834  if (shadow_pass)
835  result = md5_crypt_verify(port->user_name, shadow_pass, passwd,
836  md5Salt, 4, logdetail);
837  else
838  result = STATUS_ERROR;
839 
840  pfree(passwd);
841 
842  return result;
843 }
844 
845 static int
846 CheckSCRAMAuth(Port *port, char *shadow_pass, char **logdetail)
847 {
848  int mtype;
850  void *scram_opaq;
851  char *output = NULL;
852  int outputlen = 0;
853  int result;
854 
855  /*
856  * SASL auth is not supported for protocol versions before 3, because it
857  * relies on the overall message length word to determine the SASL payload
858  * size in AuthenticationSASLContinue and PasswordMessage messages. (We
859  * used to have a hard rule that protocol messages must be parsable
860  * without relying on the length word, but we hardly care about older
861  * protocol version anymore.)
862  */
864  ereport(FATAL,
865  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
866  errmsg("SASL authentication is not supported in protocol version 2")));
867 
868  /*
869  * Send first the authentication request to user.
870  */
872  strlen(SCRAM_SHA256_NAME) + 1);
873 
874  /*
875  * If the user doesn't exist, or doesn't have a valid password, or it's
876  * expired, we still go through the motions of SASL authentication, but
877  * tell the authentication method that the authentication is "doomed".
878  * That is, it's going to fail, no matter what.
879  *
880  * This is because we don't want to reveal to an attacker what usernames
881  * are valid, nor which users have a valid password.
882  */
883 
884  /* Initialize the status tracker for message exchanges */
885  scram_opaq = pg_be_scram_init(port->user_name, shadow_pass);
886 
887  /*
888  * Loop through SASL message exchange. This exchange can consist of
889  * multiple messages sent in both directions. First message is always
890  * from the client. All messages from client to server are password
891  * packets (type 'p').
892  */
893  do
894  {
895  pq_startmsgread();
896  mtype = pq_getbyte();
897  if (mtype != 'p')
898  {
899  /* Only log error if client didn't disconnect. */
900  if (mtype != EOF)
901  {
903  (errcode(ERRCODE_PROTOCOL_VIOLATION),
904  errmsg("expected SASL response, got message type %d",
905  mtype)));
906  return STATUS_ERROR;
907  }
908  else
909  return STATUS_EOF;
910  }
911 
912  /* Get the actual SASL message */
913  initStringInfo(&buf);
915  {
916  /* EOF - pq_getmessage already logged error */
917  pfree(buf.data);
918  return STATUS_ERROR;
919  }
920 
921  elog(DEBUG4, "Processing received SASL token of length %d", buf.len);
922 
923  /*
924  * we pass 'logdetail' as NULL when doing a mock authentication,
925  * because we should already have a better error message in that case
926  */
927  result = pg_be_scram_exchange(scram_opaq, buf.data, buf.len,
928  &output, &outputlen,
929  logdetail);
930 
931  /* input buffer no longer used */
932  pfree(buf.data);
933 
934  if (outputlen > 0)
935  {
936  /*
937  * Negotiation generated data to be sent to the client.
938  */
939  elog(DEBUG4, "sending SASL response token of length %u", outputlen);
940 
941  sendAuthRequest(port, AUTH_REQ_SASL_CONT, output, outputlen);
942  }
943  } while (result == SASL_EXCHANGE_CONTINUE);
944 
945  /* Oops, Something bad happened */
946  if (result != SASL_EXCHANGE_SUCCESS)
947  {
948  return STATUS_ERROR;
949  }
950 
951  return STATUS_OK;
952 }
953 
954 
955 /*----------------------------------------------------------------
956  * GSSAPI authentication system
957  *----------------------------------------------------------------
958  */
959 #ifdef ENABLE_GSS
960 
961 #if defined(WIN32) && !defined(WIN32_ONLY_COMPILER)
962 /*
963  * MIT Kerberos GSSAPI DLL doesn't properly export the symbols for MingW
964  * that contain the OIDs required. Redefine here, values copied
965  * from src/athena/auth/krb5/src/lib/gssapi/generic/gssapi_generic.c
966  */
967 static const gss_OID_desc GSS_C_NT_USER_NAME_desc =
968 {10, (void *) "\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x02"};
969 static GSS_DLLIMP gss_OID GSS_C_NT_USER_NAME = &GSS_C_NT_USER_NAME_desc;
970 #endif
971 
972 
973 static void
974 pg_GSS_error(int severity, char *errmsg, OM_uint32 maj_stat, OM_uint32 min_stat)
975 {
976  gss_buffer_desc gmsg;
977  OM_uint32 lmin_s,
978  msg_ctx;
979  char msg_major[128],
980  msg_minor[128];
981 
982  /* Fetch major status message */
983  msg_ctx = 0;
984  gss_display_status(&lmin_s, maj_stat, GSS_C_GSS_CODE,
985  GSS_C_NO_OID, &msg_ctx, &gmsg);
986  strlcpy(msg_major, gmsg.value, sizeof(msg_major));
987  gss_release_buffer(&lmin_s, &gmsg);
988 
989  if (msg_ctx)
990 
991  /*
992  * More than one message available. XXX: Should we loop and read all
993  * messages? (same below)
994  */
996  (errmsg_internal("incomplete GSS error report")));
997 
998  /* Fetch mechanism minor status message */
999  msg_ctx = 0;
1000  gss_display_status(&lmin_s, min_stat, GSS_C_MECH_CODE,
1001  GSS_C_NO_OID, &msg_ctx, &gmsg);
1002  strlcpy(msg_minor, gmsg.value, sizeof(msg_minor));
1003  gss_release_buffer(&lmin_s, &gmsg);
1004 
1005  if (msg_ctx)
1006  ereport(WARNING,
1007  (errmsg_internal("incomplete GSS minor error report")));
1008 
1009  /*
1010  * errmsg_internal, since translation of the first part must be done
1011  * before calling this function anyway.
1012  */
1013  ereport(severity,
1014  (errmsg_internal("%s", errmsg),
1015  errdetail_internal("%s: %s", msg_major, msg_minor)));
1016 }
1017 
1018 static int
1019 pg_GSS_recvauth(Port *port)
1020 {
1021  OM_uint32 maj_stat,
1022  min_stat,
1023  lmin_s,
1024  gflags;
1025  int mtype;
1026  int ret;
1028  gss_buffer_desc gbuf;
1029 
1030  /*
1031  * GSS auth is not supported for protocol versions before 3, because it
1032  * relies on the overall message length word to determine the GSS payload
1033  * size in AuthenticationGSSContinue and PasswordMessage messages. (This
1034  * is, in fact, a design error in our GSS support, because protocol
1035  * messages are supposed to be parsable without relying on the length
1036  * word; but it's not worth changing it now.)
1037  */
1039  ereport(FATAL,
1040  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1041  errmsg("GSSAPI is not supported in protocol version 2")));
1042 
1043  if (pg_krb_server_keyfile && strlen(pg_krb_server_keyfile) > 0)
1044  {
1045  /*
1046  * Set default Kerberos keytab file for the Krb5 mechanism.
1047  *
1048  * setenv("KRB5_KTNAME", pg_krb_server_keyfile, 0); except setenv()
1049  * not always available.
1050  */
1051  if (getenv("KRB5_KTNAME") == NULL)
1052  {
1053  size_t kt_len = strlen(pg_krb_server_keyfile) + 14;
1054  char *kt_path = malloc(kt_len);
1055 
1056  if (!kt_path ||
1057  snprintf(kt_path, kt_len, "KRB5_KTNAME=%s",
1058  pg_krb_server_keyfile) != kt_len - 2 ||
1059  putenv(kt_path) != 0)
1060  {
1061  ereport(LOG,
1062  (errcode(ERRCODE_OUT_OF_MEMORY),
1063  errmsg("out of memory")));
1064  return STATUS_ERROR;
1065  }
1066  }
1067  }
1068 
1069  /*
1070  * We accept any service principal that's present in our keytab. This
1071  * increases interoperability between kerberos implementations that see
1072  * for example case sensitivity differently, while not really opening up
1073  * any vector of attack.
1074  */
1075  port->gss->cred = GSS_C_NO_CREDENTIAL;
1076 
1077  /*
1078  * Initialize sequence with an empty context
1079  */
1080  port->gss->ctx = GSS_C_NO_CONTEXT;
1081 
1082  /*
1083  * Loop through GSSAPI message exchange. This exchange can consist of
1084  * multiple messages sent in both directions. First message is always from
1085  * the client. All messages from client to server are password packets
1086  * (type 'p').
1087  */
1088  do
1089  {
1090  pq_startmsgread();
1091 
1093 
1094  mtype = pq_getbyte();
1095  if (mtype != 'p')
1096  {
1097  /* Only log error if client didn't disconnect. */
1098  if (mtype != EOF)
1100  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1101  errmsg("expected GSS response, got message type %d",
1102  mtype)));
1103  return STATUS_ERROR;
1104  }
1105 
1106  /* Get the actual GSS token */
1107  initStringInfo(&buf);
1109  {
1110  /* EOF - pq_getmessage already logged error */
1111  pfree(buf.data);
1112  return STATUS_ERROR;
1113  }
1114 
1115  /* Map to GSSAPI style buffer */
1116  gbuf.length = buf.len;
1117  gbuf.value = buf.data;
1118 
1119  elog(DEBUG4, "Processing received GSS token of length %u",
1120  (unsigned int) gbuf.length);
1121 
1122  maj_stat = gss_accept_sec_context(
1123  &min_stat,
1124  &port->gss->ctx,
1125  port->gss->cred,
1126  &gbuf,
1127  GSS_C_NO_CHANNEL_BINDINGS,
1128  &port->gss->name,
1129  NULL,
1130  &port->gss->outbuf,
1131  &gflags,
1132  NULL,
1133  NULL);
1134 
1135  /* gbuf no longer used */
1136  pfree(buf.data);
1137 
1138  elog(DEBUG5, "gss_accept_sec_context major: %d, "
1139  "minor: %d, outlen: %u, outflags: %x",
1140  maj_stat, min_stat,
1141  (unsigned int) port->gss->outbuf.length, gflags);
1142 
1144 
1145  if (port->gss->outbuf.length != 0)
1146  {
1147  /*
1148  * Negotiation generated data to be sent to the client.
1149  */
1150  elog(DEBUG4, "sending GSS response token of length %u",
1151  (unsigned int) port->gss->outbuf.length);
1152 
1154  port->gss->outbuf.value, port->gss->outbuf.length);
1155 
1156  gss_release_buffer(&lmin_s, &port->gss->outbuf);
1157  }
1158 
1159  if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
1160  {
1161  gss_delete_sec_context(&lmin_s, &port->gss->ctx, GSS_C_NO_BUFFER);
1162  pg_GSS_error(ERROR,
1163  gettext_noop("accepting GSS security context failed"),
1164  maj_stat, min_stat);
1165  }
1166 
1167  if (maj_stat == GSS_S_CONTINUE_NEEDED)
1168  elog(DEBUG4, "GSS continue needed");
1169 
1170  } while (maj_stat == GSS_S_CONTINUE_NEEDED);
1171 
1172  if (port->gss->cred != GSS_C_NO_CREDENTIAL)
1173  {
1174  /*
1175  * Release service principal credentials
1176  */
1177  gss_release_cred(&min_stat, &port->gss->cred);
1178  }
1179 
1180  /*
1181  * GSS_S_COMPLETE indicates that authentication is now complete.
1182  *
1183  * Get the name of the user that authenticated, and compare it to the pg
1184  * username that was specified for the connection.
1185  */
1186  maj_stat = gss_display_name(&min_stat, port->gss->name, &gbuf, NULL);
1187  if (maj_stat != GSS_S_COMPLETE)
1188  pg_GSS_error(ERROR,
1189  gettext_noop("retrieving GSS user name failed"),
1190  maj_stat, min_stat);
1191 
1192  /*
1193  * Split the username at the realm separator
1194  */
1195  if (strchr(gbuf.value, '@'))
1196  {
1197  char *cp = strchr(gbuf.value, '@');
1198 
1199  /*
1200  * If we are not going to include the realm in the username that is
1201  * passed to the ident map, destructively modify it here to remove the
1202  * realm. Then advance past the separator to check the realm.
1203  */
1204  if (!port->hba->include_realm)
1205  *cp = '\0';
1206  cp++;
1207 
1208  if (port->hba->krb_realm != NULL && strlen(port->hba->krb_realm))
1209  {
1210  /*
1211  * Match the realm part of the name first
1212  */
1214  ret = pg_strcasecmp(port->hba->krb_realm, cp);
1215  else
1216  ret = strcmp(port->hba->krb_realm, cp);
1217 
1218  if (ret)
1219  {
1220  /* GSS realm does not match */
1221  elog(DEBUG2,
1222  "GSSAPI realm (%s) and configured realm (%s) don't match",
1223  cp, port->hba->krb_realm);
1224  gss_release_buffer(&lmin_s, &gbuf);
1225  return STATUS_ERROR;
1226  }
1227  }
1228  }
1229  else if (port->hba->krb_realm && strlen(port->hba->krb_realm))
1230  {
1231  elog(DEBUG2,
1232  "GSSAPI did not return realm but realm matching was requested");
1233 
1234  gss_release_buffer(&lmin_s, &gbuf);
1235  return STATUS_ERROR;
1236  }
1237 
1238  ret = check_usermap(port->hba->usermap, port->user_name, gbuf.value,
1240 
1241  gss_release_buffer(&lmin_s, &gbuf);
1242 
1243  return ret;
1244 }
1245 #endif /* ENABLE_GSS */
1246 
1247 
1248 /*----------------------------------------------------------------
1249  * SSPI authentication system
1250  *----------------------------------------------------------------
1251  */
1252 #ifdef ENABLE_SSPI
1253 static void
1254 pg_SSPI_error(int severity, const char *errmsg, SECURITY_STATUS r)
1255 {
1256  char sysmsg[256];
1257 
1258  if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
1259  FORMAT_MESSAGE_FROM_SYSTEM,
1260  NULL, r, 0,
1261  sysmsg, sizeof(sysmsg), NULL) == 0)
1262  ereport(severity,
1263  (errmsg_internal("%s", errmsg),
1264  errdetail_internal("SSPI error %x", (unsigned int) r)));
1265  else
1266  ereport(severity,
1267  (errmsg_internal("%s", errmsg),
1268  errdetail_internal("%s (%x)", sysmsg, (unsigned int) r)));
1269 }
1270 
1271 static int
1272 pg_SSPI_recvauth(Port *port)
1273 {
1274  int mtype;
1276  SECURITY_STATUS r;
1277  CredHandle sspicred;
1278  CtxtHandle *sspictx = NULL,
1279  newctx;
1280  TimeStamp expiry;
1281  ULONG contextattr;
1282  SecBufferDesc inbuf;
1283  SecBufferDesc outbuf;
1284  SecBuffer OutBuffers[1];
1285  SecBuffer InBuffers[1];
1286  HANDLE token;
1287  TOKEN_USER *tokenuser;
1288  DWORD retlen;
1289  char accountname[MAXPGPATH];
1290  char domainname[MAXPGPATH];
1291  DWORD accountnamesize = sizeof(accountname);
1292  DWORD domainnamesize = sizeof(domainname);
1293  SID_NAME_USE accountnameuse;
1294  HMODULE secur32;
1295  QUERY_SECURITY_CONTEXT_TOKEN_FN _QuerySecurityContextToken;
1296 
1297  /*
1298  * SSPI auth is not supported for protocol versions before 3, because it
1299  * relies on the overall message length word to determine the SSPI payload
1300  * size in AuthenticationGSSContinue and PasswordMessage messages. (This
1301  * is, in fact, a design error in our SSPI support, because protocol
1302  * messages are supposed to be parsable without relying on the length
1303  * word; but it's not worth changing it now.)
1304  */
1306  ereport(FATAL,
1307  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1308  errmsg("SSPI is not supported in protocol version 2")));
1309 
1310  /*
1311  * Acquire a handle to the server credentials.
1312  */
1313  r = AcquireCredentialsHandle(NULL,
1314  "negotiate",
1315  SECPKG_CRED_INBOUND,
1316  NULL,
1317  NULL,
1318  NULL,
1319  NULL,
1320  &sspicred,
1321  &expiry);
1322  if (r != SEC_E_OK)
1323  pg_SSPI_error(ERROR, _("could not acquire SSPI credentials"), r);
1324 
1325  /*
1326  * Loop through SSPI message exchange. This exchange can consist of
1327  * multiple messages sent in both directions. First message is always from
1328  * the client. All messages from client to server are password packets
1329  * (type 'p').
1330  */
1331  do
1332  {
1333  pq_startmsgread();
1334  mtype = pq_getbyte();
1335  if (mtype != 'p')
1336  {
1337  /* Only log error if client didn't disconnect. */
1338  if (mtype != EOF)
1340  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1341  errmsg("expected SSPI response, got message type %d",
1342  mtype)));
1343  return STATUS_ERROR;
1344  }
1345 
1346  /* Get the actual SSPI token */
1347  initStringInfo(&buf);
1349  {
1350  /* EOF - pq_getmessage already logged error */
1351  pfree(buf.data);
1352  return STATUS_ERROR;
1353  }
1354 
1355  /* Map to SSPI style buffer */
1356  inbuf.ulVersion = SECBUFFER_VERSION;
1357  inbuf.cBuffers = 1;
1358  inbuf.pBuffers = InBuffers;
1359  InBuffers[0].pvBuffer = buf.data;
1360  InBuffers[0].cbBuffer = buf.len;
1361  InBuffers[0].BufferType = SECBUFFER_TOKEN;
1362 
1363  /* Prepare output buffer */
1364  OutBuffers[0].pvBuffer = NULL;
1365  OutBuffers[0].BufferType = SECBUFFER_TOKEN;
1366  OutBuffers[0].cbBuffer = 0;
1367  outbuf.cBuffers = 1;
1368  outbuf.pBuffers = OutBuffers;
1369  outbuf.ulVersion = SECBUFFER_VERSION;
1370 
1371 
1372  elog(DEBUG4, "Processing received SSPI token of length %u",
1373  (unsigned int) buf.len);
1374 
1375  r = AcceptSecurityContext(&sspicred,
1376  sspictx,
1377  &inbuf,
1378  ASC_REQ_ALLOCATE_MEMORY,
1379  SECURITY_NETWORK_DREP,
1380  &newctx,
1381  &outbuf,
1382  &contextattr,
1383  NULL);
1384 
1385  /* input buffer no longer used */
1386  pfree(buf.data);
1387 
1388  if (outbuf.cBuffers > 0 && outbuf.pBuffers[0].cbBuffer > 0)
1389  {
1390  /*
1391  * Negotiation generated data to be sent to the client.
1392  */
1393  elog(DEBUG4, "sending SSPI response token of length %u",
1394  (unsigned int) outbuf.pBuffers[0].cbBuffer);
1395 
1396  port->gss->outbuf.length = outbuf.pBuffers[0].cbBuffer;
1397  port->gss->outbuf.value = outbuf.pBuffers[0].pvBuffer;
1398 
1400  port->gss->outbuf.value, port->gss->outbuf.length);
1401 
1402  FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
1403  }
1404 
1405  if (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)
1406  {
1407  if (sspictx != NULL)
1408  {
1409  DeleteSecurityContext(sspictx);
1410  free(sspictx);
1411  }
1412  FreeCredentialsHandle(&sspicred);
1413  pg_SSPI_error(ERROR,
1414  _("could not accept SSPI security context"), r);
1415  }
1416 
1417  /*
1418  * Overwrite the current context with the one we just received. If
1419  * sspictx is NULL it was the first loop and we need to allocate a
1420  * buffer for it. On subsequent runs, we can just overwrite the buffer
1421  * contents since the size does not change.
1422  */
1423  if (sspictx == NULL)
1424  {
1425  sspictx = malloc(sizeof(CtxtHandle));
1426  if (sspictx == NULL)
1427  ereport(ERROR,
1428  (errmsg("out of memory")));
1429  }
1430 
1431  memcpy(sspictx, &newctx, sizeof(CtxtHandle));
1432 
1433  if (r == SEC_I_CONTINUE_NEEDED)
1434  elog(DEBUG4, "SSPI continue needed");
1435 
1436  } while (r == SEC_I_CONTINUE_NEEDED);
1437 
1438 
1439  /*
1440  * Release service principal credentials
1441  */
1442  FreeCredentialsHandle(&sspicred);
1443 
1444 
1445  /*
1446  * SEC_E_OK indicates that authentication is now complete.
1447  *
1448  * Get the name of the user that authenticated, and compare it to the pg
1449  * username that was specified for the connection.
1450  *
1451  * MingW is missing the export for QuerySecurityContextToken in the
1452  * secur32 library, so we have to load it dynamically.
1453  */
1454 
1455  secur32 = LoadLibrary("SECUR32.DLL");
1456  if (secur32 == NULL)
1457  ereport(ERROR,
1458  (errmsg_internal("could not load secur32.dll: error code %lu",
1459  GetLastError())));
1460 
1461  _QuerySecurityContextToken = (QUERY_SECURITY_CONTEXT_TOKEN_FN)
1462  GetProcAddress(secur32, "QuerySecurityContextToken");
1463  if (_QuerySecurityContextToken == NULL)
1464  {
1465  FreeLibrary(secur32);
1466  ereport(ERROR,
1467  (errmsg_internal("could not locate QuerySecurityContextToken in secur32.dll: error code %lu",
1468  GetLastError())));
1469  }
1470 
1471  r = (_QuerySecurityContextToken) (sspictx, &token);
1472  if (r != SEC_E_OK)
1473  {
1474  FreeLibrary(secur32);
1475  pg_SSPI_error(ERROR,
1476  _("could not get token from SSPI security context"), r);
1477  }
1478 
1479  FreeLibrary(secur32);
1480 
1481  /*
1482  * No longer need the security context, everything from here on uses the
1483  * token instead.
1484  */
1485  DeleteSecurityContext(sspictx);
1486  free(sspictx);
1487 
1488  if (!GetTokenInformation(token, TokenUser, NULL, 0, &retlen) && GetLastError() != 122)
1489  ereport(ERROR,
1490  (errmsg_internal("could not get token information buffer size: error code %lu",
1491  GetLastError())));
1492 
1493  tokenuser = malloc(retlen);
1494  if (tokenuser == NULL)
1495  ereport(ERROR,
1496  (errmsg("out of memory")));
1497 
1498  if (!GetTokenInformation(token, TokenUser, tokenuser, retlen, &retlen))
1499  ereport(ERROR,
1500  (errmsg_internal("could not get token information: error code %lu",
1501  GetLastError())));
1502 
1503  CloseHandle(token);
1504 
1505  if (!LookupAccountSid(NULL, tokenuser->User.Sid, accountname, &accountnamesize,
1506  domainname, &domainnamesize, &accountnameuse))
1507  ereport(ERROR,
1508  (errmsg_internal("could not look up account SID: error code %lu",
1509  GetLastError())));
1510 
1511  free(tokenuser);
1512 
1513  if (!port->hba->compat_realm)
1514  {
1515  int status = pg_SSPI_make_upn(accountname, sizeof(accountname),
1516  domainname, sizeof(domainname),
1517  port->hba->upn_username);
1518 
1519  if (status != STATUS_OK)
1520  /* Error already reported from pg_SSPI_make_upn */
1521  return status;
1522  }
1523 
1524  /*
1525  * Compare realm/domain if requested. In SSPI, always compare case
1526  * insensitive.
1527  */
1528  if (port->hba->krb_realm && strlen(port->hba->krb_realm))
1529  {
1530  if (pg_strcasecmp(port->hba->krb_realm, domainname) != 0)
1531  {
1532  elog(DEBUG2,
1533  "SSPI domain (%s) and configured domain (%s) don't match",
1534  domainname, port->hba->krb_realm);
1535 
1536  return STATUS_ERROR;
1537  }
1538  }
1539 
1540  /*
1541  * We have the username (without domain/realm) in accountname, compare to
1542  * the supplied value. In SSPI, always compare case insensitive.
1543  *
1544  * If set to include realm, append it in <username>@<realm> format.
1545  */
1546  if (port->hba->include_realm)
1547  {
1548  char *namebuf;
1549  int retval;
1550 
1551  namebuf = psprintf("%s@%s", accountname, domainname);
1552  retval = check_usermap(port->hba->usermap, port->user_name, namebuf, true);
1553  pfree(namebuf);
1554  return retval;
1555  }
1556  else
1557  return check_usermap(port->hba->usermap, port->user_name, accountname, true);
1558 }
1559 
1560 /*
1561  * Replaces the domainname with the Kerberos realm name,
1562  * and optionally the accountname with the Kerberos user name.
1563  */
1564 static int
1565 pg_SSPI_make_upn(char *accountname,
1566  size_t accountnamesize,
1567  char *domainname,
1568  size_t domainnamesize,
1569  bool update_accountname)
1570 {
1571  char *samname;
1572  char *upname = NULL;
1573  char *p = NULL;
1574  ULONG upnamesize = 0;
1575  size_t upnamerealmsize;
1576  BOOLEAN res;
1577 
1578  /*
1579  * Build SAM name (DOMAIN\user), then translate to UPN
1580  * (user@kerberos.realm). The realm name is returned in lower case, but
1581  * that is fine because in SSPI auth, string comparisons are always
1582  * case-insensitive.
1583  */
1584 
1585  samname = psprintf("%s\\%s", domainname, accountname);
1586  res = TranslateName(samname, NameSamCompatible, NameUserPrincipal,
1587  NULL, &upnamesize);
1588 
1589  if ((!res && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1590  || upnamesize == 0)
1591  {
1592  pfree(samname);
1593  ereport(LOG,
1594  (errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1595  errmsg("could not translate name")));
1596  return STATUS_ERROR;
1597  }
1598 
1599  /* upnamesize includes the terminating NUL. */
1600  upname = palloc(upnamesize);
1601 
1602  res = TranslateName(samname, NameSamCompatible, NameUserPrincipal,
1603  upname, &upnamesize);
1604 
1605  pfree(samname);
1606  if (res)
1607  p = strchr(upname, '@');
1608 
1609  if (!res || p == NULL)
1610  {
1611  pfree(upname);
1612  ereport(LOG,
1613  (errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1614  errmsg("could not translate name")));
1615  return STATUS_ERROR;
1616  }
1617 
1618  /* Length of realm name after the '@', including the NUL. */
1619  upnamerealmsize = upnamesize - (p - upname + 1);
1620 
1621  /* Replace domainname with realm name. */
1622  if (upnamerealmsize > domainnamesize)
1623  {
1624  pfree(upname);
1625  ereport(LOG,
1626  (errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1627  errmsg("realm name too long")));
1628  return STATUS_ERROR;
1629  }
1630 
1631  /* Length is now safe. */
1632  strcpy(domainname, p + 1);
1633 
1634  /* Replace account name as well (in case UPN != SAM)? */
1635  if (update_accountname)
1636  {
1637  if ((p - upname + 1) > accountnamesize)
1638  {
1639  pfree(upname);
1640  ereport(LOG,
1641  (errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1642  errmsg("translated account name too long")));
1643  return STATUS_ERROR;
1644  }
1645 
1646  *p = 0;
1647  strcpy(accountname, upname);
1648  }
1649 
1650  pfree(upname);
1651  return STATUS_OK;
1652 }
1653 #endif /* ENABLE_SSPI */
1654 
1655 
1656 
1657 /*----------------------------------------------------------------
1658  * Ident authentication system
1659  *----------------------------------------------------------------
1660  */
1661 
1662 /*
1663  * Parse the string "*ident_response" as a response from a query to an Ident
1664  * server. If it's a normal response indicating a user name, return true
1665  * and store the user name at *ident_user. If it's anything else,
1666  * return false.
1667  */
1668 static bool
1669 interpret_ident_response(const char *ident_response,
1670  char *ident_user)
1671 {
1672  const char *cursor = ident_response; /* Cursor into *ident_response */
1673 
1674  /*
1675  * Ident's response, in the telnet tradition, should end in crlf (\r\n).
1676  */
1677  if (strlen(ident_response) < 2)
1678  return false;
1679  else if (ident_response[strlen(ident_response) - 2] != '\r')
1680  return false;
1681  else
1682  {
1683  while (*cursor != ':' && *cursor != '\r')
1684  cursor++; /* skip port field */
1685 
1686  if (*cursor != ':')
1687  return false;
1688  else
1689  {
1690  /* We're positioned to colon before response type field */
1691  char response_type[80];
1692  int i; /* Index into *response_type */
1693 
1694  cursor++; /* Go over colon */
1695  while (pg_isblank(*cursor))
1696  cursor++; /* skip blanks */
1697  i = 0;
1698  while (*cursor != ':' && *cursor != '\r' && !pg_isblank(*cursor) &&
1699  i < (int) (sizeof(response_type) - 1))
1700  response_type[i++] = *cursor++;
1701  response_type[i] = '\0';
1702  while (pg_isblank(*cursor))
1703  cursor++; /* skip blanks */
1704  if (strcmp(response_type, "USERID") != 0)
1705  return false;
1706  else
1707  {
1708  /*
1709  * It's a USERID response. Good. "cursor" should be pointing
1710  * to the colon that precedes the operating system type.
1711  */
1712  if (*cursor != ':')
1713  return false;
1714  else
1715  {
1716  cursor++; /* Go over colon */
1717  /* Skip over operating system field. */
1718  while (*cursor != ':' && *cursor != '\r')
1719  cursor++;
1720  if (*cursor != ':')
1721  return false;
1722  else
1723  {
1724  int i; /* Index into *ident_user */
1725 
1726  cursor++; /* Go over colon */
1727  while (pg_isblank(*cursor))
1728  cursor++; /* skip blanks */
1729  /* Rest of line is user name. Copy it over. */
1730  i = 0;
1731  while (*cursor != '\r' && i < IDENT_USERNAME_MAX)
1732  ident_user[i++] = *cursor++;
1733  ident_user[i] = '\0';
1734  return true;
1735  }
1736  }
1737  }
1738  }
1739  }
1740 }
1741 
1742 
1743 /*
1744  * Talk to the ident server on host "remote_ip_addr" and find out who
1745  * owns the tcp connection from his port "remote_port" to port
1746  * "local_port_addr" on host "local_ip_addr". Return the user name the
1747  * ident server gives as "*ident_user".
1748  *
1749  * IP addresses and port numbers are in network byte order.
1750  *
1751  * But iff we're unable to get the information from ident, return false.
1752  *
1753  * XXX: Using WaitLatchOrSocket() and doing a CHECK_FOR_INTERRUPTS() if the
1754  * latch was set would improve the responsiveness to timeouts/cancellations.
1755  */
1756 static int
1758 {
1759  const SockAddr remote_addr = port->raddr;
1760  const SockAddr local_addr = port->laddr;
1761  char ident_user[IDENT_USERNAME_MAX + 1];
1762  pgsocket sock_fd = PGINVALID_SOCKET; /* for talking to Ident server */
1763  int rc; /* Return code from a locally called function */
1764  bool ident_return;
1765  char remote_addr_s[NI_MAXHOST];
1766  char remote_port[NI_MAXSERV];
1767  char local_addr_s[NI_MAXHOST];
1768  char local_port[NI_MAXSERV];
1769  char ident_port[NI_MAXSERV];
1770  char ident_query[80];
1771  char ident_response[80 + IDENT_USERNAME_MAX];
1772  struct addrinfo *ident_serv = NULL,
1773  *la = NULL,
1774  hints;
1775 
1776  /*
1777  * Might look a little weird to first convert it to text and then back to
1778  * sockaddr, but it's protocol independent.
1779  */
1780  pg_getnameinfo_all(&remote_addr.addr, remote_addr.salen,
1781  remote_addr_s, sizeof(remote_addr_s),
1782  remote_port, sizeof(remote_port),
1784  pg_getnameinfo_all(&local_addr.addr, local_addr.salen,
1785  local_addr_s, sizeof(local_addr_s),
1786  local_port, sizeof(local_port),
1788 
1789  snprintf(ident_port, sizeof(ident_port), "%d", IDENT_PORT);
1790  hints.ai_flags = AI_NUMERICHOST;
1791  hints.ai_family = remote_addr.addr.ss_family;
1792  hints.ai_socktype = SOCK_STREAM;
1793  hints.ai_protocol = 0;
1794  hints.ai_addrlen = 0;
1795  hints.ai_canonname = NULL;
1796  hints.ai_addr = NULL;
1797  hints.ai_next = NULL;
1798  rc = pg_getaddrinfo_all(remote_addr_s, ident_port, &hints, &ident_serv);
1799  if (rc || !ident_serv)
1800  {
1801  /* we don't expect this to happen */
1802  ident_return = false;
1803  goto ident_inet_done;
1804  }
1805 
1806  hints.ai_flags = AI_NUMERICHOST;
1807  hints.ai_family = local_addr.addr.ss_family;
1808  hints.ai_socktype = SOCK_STREAM;
1809  hints.ai_protocol = 0;
1810  hints.ai_addrlen = 0;
1811  hints.ai_canonname = NULL;
1812  hints.ai_addr = NULL;
1813  hints.ai_next = NULL;
1814  rc = pg_getaddrinfo_all(local_addr_s, NULL, &hints, &la);
1815  if (rc || !la)
1816  {
1817  /* we don't expect this to happen */
1818  ident_return = false;
1819  goto ident_inet_done;
1820  }
1821 
1822  sock_fd = socket(ident_serv->ai_family, ident_serv->ai_socktype,
1823  ident_serv->ai_protocol);
1824  if (sock_fd == PGINVALID_SOCKET)
1825  {
1826  ereport(LOG,
1828  errmsg("could not create socket for Ident connection: %m")));
1829  ident_return = false;
1830  goto ident_inet_done;
1831  }
1832 
1833  /*
1834  * Bind to the address which the client originally contacted, otherwise
1835  * the ident server won't be able to match up the right connection. This
1836  * is necessary if the PostgreSQL server is running on an IP alias.
1837  */
1838  rc = bind(sock_fd, la->ai_addr, la->ai_addrlen);
1839  if (rc != 0)
1840  {
1841  ereport(LOG,
1843  errmsg("could not bind to local address \"%s\": %m",
1844  local_addr_s)));
1845  ident_return = false;
1846  goto ident_inet_done;
1847  }
1848 
1849  rc = connect(sock_fd, ident_serv->ai_addr,
1850  ident_serv->ai_addrlen);
1851  if (rc != 0)
1852  {
1853  ereport(LOG,
1855  errmsg("could not connect to Ident server at address \"%s\", port %s: %m",
1856  remote_addr_s, ident_port)));
1857  ident_return = false;
1858  goto ident_inet_done;
1859  }
1860 
1861  /* The query we send to the Ident server */
1862  snprintf(ident_query, sizeof(ident_query), "%s,%s\r\n",
1863  remote_port, local_port);
1864 
1865  /* loop in case send is interrupted */
1866  do
1867  {
1869 
1870  rc = send(sock_fd, ident_query, strlen(ident_query), 0);
1871  } while (rc < 0 && errno == EINTR);
1872 
1873  if (rc < 0)
1874  {
1875  ereport(LOG,
1877  errmsg("could not send query to Ident server at address \"%s\", port %s: %m",
1878  remote_addr_s, ident_port)));
1879  ident_return = false;
1880  goto ident_inet_done;
1881  }
1882 
1883  do
1884  {
1886 
1887  rc = recv(sock_fd, ident_response, sizeof(ident_response) - 1, 0);
1888  } while (rc < 0 && errno == EINTR);
1889 
1890  if (rc < 0)
1891  {
1892  ereport(LOG,
1894  errmsg("could not receive response from Ident server at address \"%s\", port %s: %m",
1895  remote_addr_s, ident_port)));
1896  ident_return = false;
1897  goto ident_inet_done;
1898  }
1899 
1900  ident_response[rc] = '\0';
1901  ident_return = interpret_ident_response(ident_response, ident_user);
1902  if (!ident_return)
1903  ereport(LOG,
1904  (errmsg("invalidly formatted response from Ident server: \"%s\"",
1905  ident_response)));
1906 
1907 ident_inet_done:
1908  if (sock_fd != PGINVALID_SOCKET)
1909  closesocket(sock_fd);
1910  if (ident_serv)
1911  pg_freeaddrinfo_all(remote_addr.addr.ss_family, ident_serv);
1912  if (la)
1913  pg_freeaddrinfo_all(local_addr.addr.ss_family, la);
1914 
1915  if (ident_return)
1916  /* Success! Check the usermap */
1917  return check_usermap(port->hba->usermap, port->user_name, ident_user, false);
1918  return STATUS_ERROR;
1919 }
1920 
1921 /*
1922  * Ask kernel about the credentials of the connecting process,
1923  * determine the symbolic name of the corresponding user, and check
1924  * if valid per the usermap.
1925  *
1926  * Iff authorized, return STATUS_OK, otherwise return STATUS_ERROR.
1927  */
1928 #ifdef HAVE_UNIX_SOCKETS
1929 
1930 static int
1931 auth_peer(hbaPort *port)
1932 {
1933  char ident_user[IDENT_USERNAME_MAX + 1];
1934  uid_t uid;
1935  gid_t gid;
1936  struct passwd *pw;
1937 
1938  if (getpeereid(port->sock, &uid, &gid) != 0)
1939  {
1940  /* Provide special error message if getpeereid is a stub */
1941  if (errno == ENOSYS)
1942  ereport(LOG,
1943  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1944  errmsg("peer authentication is not supported on this platform")));
1945  else
1946  ereport(LOG,
1948  errmsg("could not get peer credentials: %m")));
1949  return STATUS_ERROR;
1950  }
1951 
1952  errno = 0; /* clear errno before call */
1953  pw = getpwuid(uid);
1954  if (!pw)
1955  {
1956  ereport(LOG,
1957  (errmsg("could not look up local user ID %ld: %s",
1958  (long) uid,
1959  errno ? strerror(errno) : _("user does not exist"))));
1960  return STATUS_ERROR;
1961  }
1962 
1963  strlcpy(ident_user, pw->pw_name, IDENT_USERNAME_MAX + 1);
1964 
1965  return check_usermap(port->hba->usermap, port->user_name, ident_user, false);
1966 }
1967 #endif /* HAVE_UNIX_SOCKETS */
1968 
1969 
1970 /*----------------------------------------------------------------
1971  * PAM authentication system
1972  *----------------------------------------------------------------
1973  */
1974 #ifdef USE_PAM
1975 
1976 /*
1977  * PAM conversation function
1978  */
1979 
1980 static int
1981 pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg,
1982  struct pam_response ** resp, void *appdata_ptr)
1983 {
1984  char *passwd;
1985  struct pam_response *reply;
1986  int i;
1987 
1988  if (appdata_ptr)
1989  passwd = (char *) appdata_ptr;
1990  else
1991  {
1992  /*
1993  * Workaround for Solaris 2.6 where the PAM library is broken and does
1994  * not pass appdata_ptr to the conversation routine
1995  */
1996  passwd = pam_passwd;
1997  }
1998 
1999  *resp = NULL; /* in case of error exit */
2000 
2001  if (num_msg <= 0 || num_msg > PAM_MAX_NUM_MSG)
2002  return PAM_CONV_ERR;
2003 
2004  /*
2005  * Explicitly not using palloc here - PAM will free this memory in
2006  * pam_end()
2007  */
2008  if ((reply = calloc(num_msg, sizeof(struct pam_response))) == NULL)
2009  {
2010  ereport(LOG,
2011  (errcode(ERRCODE_OUT_OF_MEMORY),
2012  errmsg("out of memory")));
2013  return PAM_CONV_ERR;
2014  }
2015 
2016  for (i = 0; i < num_msg; i++)
2017  {
2018  switch (msg[i]->msg_style)
2019  {
2020  case PAM_PROMPT_ECHO_OFF:
2021  if (strlen(passwd) == 0)
2022  {
2023  /*
2024  * Password wasn't passed to PAM the first time around -
2025  * let's go ask the client to send a password, which we
2026  * then stuff into PAM.
2027  */
2028  sendAuthRequest(pam_port_cludge, AUTH_REQ_PASSWORD, NULL, 0);
2029  passwd = recv_password_packet(pam_port_cludge);
2030  if (passwd == NULL)
2031  {
2032  /*
2033  * Client didn't want to send password. We
2034  * intentionally do not log anything about this.
2035  */
2036  goto fail;
2037  }
2038  if (strlen(passwd) == 0)
2039  {
2040  ereport(LOG,
2041  (errmsg("empty password returned by client")));
2042  goto fail;
2043  }
2044  }
2045  if ((reply[i].resp = strdup(passwd)) == NULL)
2046  goto fail;
2047  reply[i].resp_retcode = PAM_SUCCESS;
2048  break;
2049  case PAM_ERROR_MSG:
2050  ereport(LOG,
2051  (errmsg("error from underlying PAM layer: %s",
2052  msg[i]->msg)));
2053  /* FALL THROUGH */
2054  case PAM_TEXT_INFO:
2055  /* we don't bother to log TEXT_INFO messages */
2056  if ((reply[i].resp = strdup("")) == NULL)
2057  goto fail;
2058  reply[i].resp_retcode = PAM_SUCCESS;
2059  break;
2060  default:
2061  elog(LOG, "unsupported PAM conversation %d/\"%s\"",
2062  msg[i]->msg_style,
2063  msg[i]->msg ? msg[i]->msg : "(none)");
2064  goto fail;
2065  }
2066  }
2067 
2068  *resp = reply;
2069  return PAM_SUCCESS;
2070 
2071 fail:
2072  /* free up whatever we allocated */
2073  for (i = 0; i < num_msg; i++)
2074  {
2075  if (reply[i].resp != NULL)
2076  free(reply[i].resp);
2077  }
2078  free(reply);
2079 
2080  return PAM_CONV_ERR;
2081 }
2082 
2083 
2084 /*
2085  * Check authentication against PAM.
2086  */
2087 static int
2088 CheckPAMAuth(Port *port, char *user, char *password)
2089 {
2090  int retval;
2091  pam_handle_t *pamh = NULL;
2092  char hostinfo[NI_MAXHOST];
2093 
2094  retval = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2095  hostinfo, sizeof(hostinfo), NULL, 0,
2097  if (retval != 0)
2098  {
2099  ereport(WARNING,
2100  (errmsg_internal("pg_getnameinfo_all() failed: %s",
2101  gai_strerror(retval))));
2102  return STATUS_ERROR;
2103  }
2104 
2105  /*
2106  * We can't entirely rely on PAM to pass through appdata --- it appears
2107  * not to work on at least Solaris 2.6. So use these ugly static
2108  * variables instead.
2109  */
2110  pam_passwd = password;
2111  pam_port_cludge = port;
2112 
2113  /*
2114  * Set the application data portion of the conversation struct. This is
2115  * later used inside the PAM conversation to pass the password to the
2116  * authentication module.
2117  */
2118  pam_passw_conv.appdata_ptr = (char *) password; /* from password above,
2119  * not allocated */
2120 
2121  /* Optionally, one can set the service name in pg_hba.conf */
2122  if (port->hba->pamservice && port->hba->pamservice[0] != '\0')
2123  retval = pam_start(port->hba->pamservice, "pgsql@",
2124  &pam_passw_conv, &pamh);
2125  else
2126  retval = pam_start(PGSQL_PAM_SERVICE, "pgsql@",
2127  &pam_passw_conv, &pamh);
2128 
2129  if (retval != PAM_SUCCESS)
2130  {
2131  ereport(LOG,
2132  (errmsg("could not create PAM authenticator: %s",
2133  pam_strerror(pamh, retval))));
2134  pam_passwd = NULL; /* Unset pam_passwd */
2135  return STATUS_ERROR;
2136  }
2137 
2138  retval = pam_set_item(pamh, PAM_USER, user);
2139 
2140  if (retval != PAM_SUCCESS)
2141  {
2142  ereport(LOG,
2143  (errmsg("pam_set_item(PAM_USER) failed: %s",
2144  pam_strerror(pamh, retval))));
2145  pam_passwd = NULL; /* Unset pam_passwd */
2146  return STATUS_ERROR;
2147  }
2148 
2149  retval = pam_set_item(pamh, PAM_RHOST, hostinfo);
2150 
2151  if (retval != PAM_SUCCESS)
2152  {
2153  ereport(LOG,
2154  (errmsg("pam_set_item(PAM_RHOST) failed: %s",
2155  pam_strerror(pamh, retval))));
2156  pam_passwd = NULL;
2157  return STATUS_ERROR;
2158  }
2159 
2160  retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv);
2161 
2162  if (retval != PAM_SUCCESS)
2163  {
2164  ereport(LOG,
2165  (errmsg("pam_set_item(PAM_CONV) failed: %s",
2166  pam_strerror(pamh, retval))));
2167  pam_passwd = NULL; /* Unset pam_passwd */
2168  return STATUS_ERROR;
2169  }
2170 
2171  retval = pam_authenticate(pamh, 0);
2172 
2173  if (retval != PAM_SUCCESS)
2174  {
2175  ereport(LOG,
2176  (errmsg("pam_authenticate failed: %s",
2177  pam_strerror(pamh, retval))));
2178  pam_passwd = NULL; /* Unset pam_passwd */
2179  return STATUS_ERROR;
2180  }
2181 
2182  retval = pam_acct_mgmt(pamh, 0);
2183 
2184  if (retval != PAM_SUCCESS)
2185  {
2186  ereport(LOG,
2187  (errmsg("pam_acct_mgmt failed: %s",
2188  pam_strerror(pamh, retval))));
2189  pam_passwd = NULL; /* Unset pam_passwd */
2190  return STATUS_ERROR;
2191  }
2192 
2193  retval = pam_end(pamh, retval);
2194 
2195  if (retval != PAM_SUCCESS)
2196  {
2197  ereport(LOG,
2198  (errmsg("could not release PAM authenticator: %s",
2199  pam_strerror(pamh, retval))));
2200  }
2201 
2202  pam_passwd = NULL; /* Unset pam_passwd */
2203 
2204  return (retval == PAM_SUCCESS ? STATUS_OK : STATUS_ERROR);
2205 }
2206 #endif /* USE_PAM */
2207 
2208 
2209 /*----------------------------------------------------------------
2210  * BSD authentication system
2211  *----------------------------------------------------------------
2212  */
2213 #ifdef USE_BSD_AUTH
2214 static int
2215 CheckBSDAuth(Port *port, char *user)
2216 {
2217  char *passwd;
2218  int retval;
2219 
2220  /* Send regular password request to client, and get the response */
2222 
2223  passwd = recv_password_packet(port);
2224  if (passwd == NULL)
2225  return STATUS_EOF;
2226 
2227  /*
2228  * Ask the BSD auth system to verify password. Note that auth_userokay
2229  * will overwrite the password string with zeroes, but it's just a
2230  * temporary string so we don't care.
2231  */
2232  retval = auth_userokay(user, NULL, "auth-postgresql", passwd);
2233 
2234  if (!retval)
2235  return STATUS_ERROR;
2236 
2237  return STATUS_OK;
2238 }
2239 #endif /* USE_BSD_AUTH */
2240 
2241 
2242 /*----------------------------------------------------------------
2243  * LDAP authentication system
2244  *----------------------------------------------------------------
2245  */
2246 #ifdef USE_LDAP
2247 
2248 /*
2249  * Initialize a connection to the LDAP server, including setting up
2250  * TLS if requested.
2251  */
2252 static int
2253 InitializeLDAPConnection(Port *port, LDAP **ldap)
2254 {
2255  int ldapversion = LDAP_VERSION3;
2256  int r;
2257 
2258  *ldap = ldap_init(port->hba->ldapserver, port->hba->ldapport);
2259  if (!*ldap)
2260  {
2261 #ifndef WIN32
2262  ereport(LOG,
2263  (errmsg("could not initialize LDAP: %m")));
2264 #else
2265  ereport(LOG,
2266  (errmsg("could not initialize LDAP: error code %d",
2267  (int) LdapGetLastError())));
2268 #endif
2269  return STATUS_ERROR;
2270  }
2271 
2272  if ((r = ldap_set_option(*ldap, LDAP_OPT_PROTOCOL_VERSION, &ldapversion)) != LDAP_SUCCESS)
2273  {
2274  ldap_unbind(*ldap);
2275  ereport(LOG,
2276  (errmsg("could not set LDAP protocol version: %s", ldap_err2string(r))));
2277  return STATUS_ERROR;
2278  }
2279 
2280  if (port->hba->ldaptls)
2281  {
2282 #ifndef WIN32
2283  if ((r = ldap_start_tls_s(*ldap, NULL, NULL)) != LDAP_SUCCESS)
2284 #else
2285  static __ldap_start_tls_sA _ldap_start_tls_sA = NULL;
2286 
2287  if (_ldap_start_tls_sA == NULL)
2288  {
2289  /*
2290  * Need to load this function dynamically because it does not
2291  * exist on Windows 2000, and causes a load error for the whole
2292  * exe if referenced.
2293  */
2294  HANDLE ldaphandle;
2295 
2296  ldaphandle = LoadLibrary("WLDAP32.DLL");
2297  if (ldaphandle == NULL)
2298  {
2299  /*
2300  * should never happen since we import other files from
2301  * wldap32, but check anyway
2302  */
2303  ldap_unbind(*ldap);
2304  ereport(LOG,
2305  (errmsg("could not load wldap32.dll")));
2306  return STATUS_ERROR;
2307  }
2308  _ldap_start_tls_sA = (__ldap_start_tls_sA) GetProcAddress(ldaphandle, "ldap_start_tls_sA");
2309  if (_ldap_start_tls_sA == NULL)
2310  {
2311  ldap_unbind(*ldap);
2312  ereport(LOG,
2313  (errmsg("could not load function _ldap_start_tls_sA in wldap32.dll"),
2314  errdetail("LDAP over SSL is not supported on this platform.")));
2315  return STATUS_ERROR;
2316  }
2317 
2318  /*
2319  * Leak LDAP handle on purpose, because we need the library to
2320  * stay open. This is ok because it will only ever be leaked once
2321  * per process and is automatically cleaned up on process exit.
2322  */
2323  }
2324  if ((r = _ldap_start_tls_sA(*ldap, NULL, NULL, NULL, NULL)) != LDAP_SUCCESS)
2325 #endif
2326  {
2327  ldap_unbind(*ldap);
2328  ereport(LOG,
2329  (errmsg("could not start LDAP TLS session: %s", ldap_err2string(r))));
2330  return STATUS_ERROR;
2331  }
2332  }
2333 
2334  return STATUS_OK;
2335 }
2336 
2337 /*
2338  * Perform LDAP authentication
2339  */
2340 static int
2341 CheckLDAPAuth(Port *port)
2342 {
2343  char *passwd;
2344  LDAP *ldap;
2345  int r;
2346  char *fulluser;
2347 
2348  if (!port->hba->ldapserver || port->hba->ldapserver[0] == '\0')
2349  {
2350  ereport(LOG,
2351  (errmsg("LDAP server not specified")));
2352  return STATUS_ERROR;
2353  }
2354 
2355  if (port->hba->ldapport == 0)
2356  port->hba->ldapport = LDAP_PORT;
2357 
2359 
2360  passwd = recv_password_packet(port);
2361  if (passwd == NULL)
2362  return STATUS_EOF; /* client wouldn't send password */
2363 
2364  if (strlen(passwd) == 0)
2365  {
2366  ereport(LOG,
2367  (errmsg("empty password returned by client")));
2368  return STATUS_ERROR;
2369  }
2370 
2371  if (InitializeLDAPConnection(port, &ldap) == STATUS_ERROR)
2372  /* Error message already sent */
2373  return STATUS_ERROR;
2374 
2375  if (port->hba->ldapbasedn)
2376  {
2377  /*
2378  * First perform an LDAP search to find the DN for the user we are
2379  * trying to log in as.
2380  */
2381  char *filter;
2382  LDAPMessage *search_message;
2383  LDAPMessage *entry;
2384  char *attributes[2];
2385  char *dn;
2386  char *c;
2387  int count;
2388 
2389  /*
2390  * Disallow any characters that we would otherwise need to escape,
2391  * since they aren't really reasonable in a username anyway. Allowing
2392  * them would make it possible to inject any kind of custom filters in
2393  * the LDAP filter.
2394  */
2395  for (c = port->user_name; *c; c++)
2396  {
2397  if (*c == '*' ||
2398  *c == '(' ||
2399  *c == ')' ||
2400  *c == '\\' ||
2401  *c == '/')
2402  {
2403  ereport(LOG,
2404  (errmsg("invalid character in user name for LDAP authentication")));
2405  return STATUS_ERROR;
2406  }
2407  }
2408 
2409  /*
2410  * Bind with a pre-defined username/password (if available) for
2411  * searching. If none is specified, this turns into an anonymous bind.
2412  */
2413  r = ldap_simple_bind_s(ldap,
2414  port->hba->ldapbinddn ? port->hba->ldapbinddn : "",
2415  port->hba->ldapbindpasswd ? port->hba->ldapbindpasswd : "");
2416  if (r != LDAP_SUCCESS)
2417  {
2418  ereport(LOG,
2419  (errmsg("could not perform initial LDAP bind for ldapbinddn \"%s\" on server \"%s\": %s",
2420  port->hba->ldapbinddn, port->hba->ldapserver, ldap_err2string(r))));
2421  return STATUS_ERROR;
2422  }
2423 
2424  /* Fetch just one attribute, else *all* attributes are returned */
2425  attributes[0] = port->hba->ldapsearchattribute ? port->hba->ldapsearchattribute : "uid";
2426  attributes[1] = NULL;
2427 
2428  filter = psprintf("(%s=%s)",
2429  attributes[0],
2430  port->user_name);
2431 
2432  r = ldap_search_s(ldap,
2433  port->hba->ldapbasedn,
2434  port->hba->ldapscope,
2435  filter,
2436  attributes,
2437  0,
2438  &search_message);
2439 
2440  if (r != LDAP_SUCCESS)
2441  {
2442  ereport(LOG,
2443  (errmsg("could not search LDAP for filter \"%s\" on server \"%s\": %s",
2444  filter, port->hba->ldapserver, ldap_err2string(r))));
2445  pfree(filter);
2446  return STATUS_ERROR;
2447  }
2448 
2449  count = ldap_count_entries(ldap, search_message);
2450  if (count != 1)
2451  {
2452  if (count == 0)
2453  ereport(LOG,
2454  (errmsg("LDAP user \"%s\" does not exist", port->user_name),
2455  errdetail("LDAP search for filter \"%s\" on server \"%s\" returned no entries.",
2456  filter, port->hba->ldapserver)));
2457  else
2458  ereport(LOG,
2459  (errmsg("LDAP user \"%s\" is not unique", port->user_name),
2460  errdetail_plural("LDAP search for filter \"%s\" on server \"%s\" returned %d entry.",
2461  "LDAP search for filter \"%s\" on server \"%s\" returned %d entries.",
2462  count,
2463  filter, port->hba->ldapserver, count)));
2464 
2465  pfree(filter);
2466  ldap_msgfree(search_message);
2467  return STATUS_ERROR;
2468  }
2469 
2470  entry = ldap_first_entry(ldap, search_message);
2471  dn = ldap_get_dn(ldap, entry);
2472  if (dn == NULL)
2473  {
2474  int error;
2475 
2476  (void) ldap_get_option(ldap, LDAP_OPT_ERROR_NUMBER, &error);
2477  ereport(LOG,
2478  (errmsg("could not get dn for the first entry matching \"%s\" on server \"%s\": %s",
2479  filter, port->hba->ldapserver, ldap_err2string(error))));
2480  pfree(filter);
2481  ldap_msgfree(search_message);
2482  return STATUS_ERROR;
2483  }
2484  fulluser = pstrdup(dn);
2485 
2486  pfree(filter);
2487  ldap_memfree(dn);
2488  ldap_msgfree(search_message);
2489 
2490  /* Unbind and disconnect from the LDAP server */
2491  r = ldap_unbind_s(ldap);
2492  if (r != LDAP_SUCCESS)
2493  {
2494  int error;
2495 
2496  (void) ldap_get_option(ldap, LDAP_OPT_ERROR_NUMBER, &error);
2497  ereport(LOG,
2498  (errmsg("could not unbind after searching for user \"%s\" on server \"%s\": %s",
2499  fulluser, port->hba->ldapserver, ldap_err2string(error))));
2500  pfree(fulluser);
2501  return STATUS_ERROR;
2502  }
2503 
2504  /*
2505  * Need to re-initialize the LDAP connection, so that we can bind to
2506  * it with a different username.
2507  */
2508  if (InitializeLDAPConnection(port, &ldap) == STATUS_ERROR)
2509  {
2510  pfree(fulluser);
2511 
2512  /* Error message already sent */
2513  return STATUS_ERROR;
2514  }
2515  }
2516  else
2517  fulluser = psprintf("%s%s%s",
2518  port->hba->ldapprefix ? port->hba->ldapprefix : "",
2519  port->user_name,
2520  port->hba->ldapsuffix ? port->hba->ldapsuffix : "");
2521 
2522  r = ldap_simple_bind_s(ldap, fulluser, passwd);
2523  ldap_unbind(ldap);
2524 
2525  if (r != LDAP_SUCCESS)
2526  {
2527  ereport(LOG,
2528  (errmsg("LDAP login failed for user \"%s\" on server \"%s\": %s",
2529  fulluser, port->hba->ldapserver, ldap_err2string(r))));
2530  pfree(fulluser);
2531  return STATUS_ERROR;
2532  }
2533 
2534  pfree(fulluser);
2535 
2536  return STATUS_OK;
2537 }
2538 #endif /* USE_LDAP */
2539 
2540 
2541 /*----------------------------------------------------------------
2542  * SSL client certificate authentication
2543  *----------------------------------------------------------------
2544  */
2545 #ifdef USE_SSL
2546 static int
2547 CheckCertAuth(Port *port)
2548 {
2549  Assert(port->ssl);
2550 
2551  /* Make sure we have received a username in the certificate */
2552  if (port->peer_cn == NULL ||
2553  strlen(port->peer_cn) <= 0)
2554  {
2555  ereport(LOG,
2556  (errmsg("certificate authentication failed for user \"%s\": client certificate contains no user name",
2557  port->user_name)));
2558  return STATUS_ERROR;
2559  }
2560 
2561  /* Just pass the certificate CN to the usermap check */
2562  return check_usermap(port->hba->usermap, port->user_name, port->peer_cn, false);
2563 }
2564 #endif
2565 
2566 
2567 /*----------------------------------------------------------------
2568  * RADIUS authentication
2569  *----------------------------------------------------------------
2570  */
2571 
2572 /*
2573  * RADIUS authentication is described in RFC2865 (and several others).
2574  */
2575 
2576 #define RADIUS_VECTOR_LENGTH 16
2577 #define RADIUS_HEADER_LENGTH 20
2578 #define RADIUS_MAX_PASSWORD_LENGTH 128
2579 
2580 /* Maximum size of a RADIUS packet we will create or accept */
2581 #define RADIUS_BUFFER_SIZE 1024
2582 
2583 typedef struct
2584 {
2587  uint8 data[FLEXIBLE_ARRAY_MEMBER];
2589 
2590 typedef struct
2591 {
2596  /* this is a bit longer than strictly necessary: */
2598 } radius_packet;
2599 
2600 /* RADIUS packet types */
2601 #define RADIUS_ACCESS_REQUEST 1
2602 #define RADIUS_ACCESS_ACCEPT 2
2603 #define RADIUS_ACCESS_REJECT 3
2604 
2605 /* RAIDUS attributes */
2606 #define RADIUS_USER_NAME 1
2607 #define RADIUS_PASSWORD 2
2608 #define RADIUS_SERVICE_TYPE 6
2609 #define RADIUS_NAS_IDENTIFIER 32
2610 
2611 /* RADIUS service types */
2612 #define RADIUS_AUTHENTICATE_ONLY 8
2613 
2614 /* Seconds to wait - XXX: should be in a config variable! */
2615 #define RADIUS_TIMEOUT 3
2616 
2617 static void
2618 radius_add_attribute(radius_packet *packet, uint8 type, const unsigned char *data, int len)
2619 {
2620  radius_attribute *attr;
2621 
2622  if (packet->length + len > RADIUS_BUFFER_SIZE)
2623  {
2624  /*
2625  * With remotely realistic data, this can never happen. But catch it
2626  * just to make sure we don't overrun a buffer. We'll just skip adding
2627  * the broken attribute, which will in the end cause authentication to
2628  * fail.
2629  */
2630  elog(WARNING,
2631  "Adding attribute code %d with length %d to radius packet would create oversize packet, ignoring",
2632  type, len);
2633  return;
2634  }
2635 
2636  attr = (radius_attribute *) ((unsigned char *) packet + packet->length);
2637  attr->attribute = type;
2638  attr->length = len + 2; /* total size includes type and length */
2639  memcpy(attr->data, data, len);
2640  packet->length += attr->length;
2641 }
2642 
2643 static int
2645 {
2646  char *passwd;
2647  ListCell *server,
2648  *secrets,
2649  *radiusports,
2650  *identifiers;
2651 
2652  /* Make sure struct alignment is correct */
2653  Assert(offsetof(radius_packet, vector) == 4);
2654 
2655  /* Verify parameters */
2656  if (list_length(port->hba->radiusservers) < 1)
2657  {
2658  ereport(LOG,
2659  (errmsg("RADIUS server not specified")));
2660  return STATUS_ERROR;
2661  }
2662 
2663  if (list_length(port->hba->radiussecrets) < 1)
2664  {
2665  ereport(LOG,
2666  (errmsg("RADIUS secret not specified")));
2667  return STATUS_ERROR;
2668  }
2669 
2670  /* Send regular password request to client, and get the response */
2672 
2673  passwd = recv_password_packet(port);
2674  if (passwd == NULL)
2675  return STATUS_EOF; /* client wouldn't send password */
2676 
2677  if (strlen(passwd) == 0)
2678  {
2679  ereport(LOG,
2680  (errmsg("empty password returned by client")));
2681  return STATUS_ERROR;
2682  }
2683 
2684  if (strlen(passwd) > RADIUS_MAX_PASSWORD_LENGTH)
2685  {
2686  ereport(LOG,
2687  (errmsg("RADIUS authentication does not support passwords longer than %d characters", RADIUS_MAX_PASSWORD_LENGTH)));
2688  return STATUS_ERROR;
2689  }
2690 
2691  /*
2692  * Loop over and try each server in order.
2693  */
2694  secrets = list_head(port->hba->radiussecrets);
2695  radiusports = list_head(port->hba->radiusports);
2696  identifiers = list_head(port->hba->radiusidentifiers);
2697  foreach(server, port->hba->radiusservers)
2698  {
2699  int ret = PerformRadiusTransaction(lfirst(server),
2700  lfirst(secrets),
2701  radiusports ? lfirst(radiusports) : NULL,
2702  identifiers ? lfirst(identifiers) : NULL,
2703  port->user_name,
2704  passwd);
2705 
2706  /*------
2707  * STATUS_OK = Login OK
2708  * STATUS_ERROR = Login not OK, but try next server
2709  * STATUS_EOF = Login not OK, and don't try next server
2710  *------
2711  */
2712  if (ret == STATUS_OK)
2713  return STATUS_OK;
2714  else if (ret == STATUS_EOF)
2715  return STATUS_ERROR;
2716 
2717  /*
2718  * secret, port and identifiers either have length 0 (use default),
2719  * length 1 (use the same everywhere) or the same length as servers.
2720  * So if the length is >1, we advance one step. In other cases, we
2721  * don't and will then reuse the correct value.
2722  */
2723  if (list_length(port->hba->radiussecrets) > 1)
2724  secrets = lnext(secrets);
2725  if (list_length(port->hba->radiusports) > 1)
2726  radiusports = lnext(radiusports);
2727  if (list_length(port->hba->radiusidentifiers) > 1)
2728  identifiers = lnext(identifiers);
2729  }
2730 
2731  /* No servers left to try, so give up */
2732  return STATUS_ERROR;
2733 }
2734 
2735 static int
2736 PerformRadiusTransaction(char *server, char *secret, char *portstr, char *identifier, char *user_name, char *passwd)
2737 {
2738  radius_packet radius_send_pack;
2739  radius_packet radius_recv_pack;
2740  radius_packet *packet = &radius_send_pack;
2741  radius_packet *receivepacket = &radius_recv_pack;
2742  char *radius_buffer = (char *) &radius_send_pack;
2743  char *receive_buffer = (char *) &radius_recv_pack;
2744  int32 service = htonl(RADIUS_AUTHENTICATE_ONLY);
2745  uint8 *cryptvector;
2746  int encryptedpasswordlen;
2747  uint8 encryptedpassword[RADIUS_MAX_PASSWORD_LENGTH];
2748  uint8 *md5trailer;
2749  int packetlength;
2750  pgsocket sock;
2751 
2752 #ifdef HAVE_IPV6
2753  struct sockaddr_in6 localaddr;
2754  struct sockaddr_in6 remoteaddr;
2755 #else
2756  struct sockaddr_in localaddr;
2757  struct sockaddr_in remoteaddr;
2758 #endif
2759  struct addrinfo hint;
2760  struct addrinfo *serveraddrs;
2761  int port;
2762  ACCEPT_TYPE_ARG3 addrsize;
2763  fd_set fdset;
2764  struct timeval endtime;
2765  int i,
2766  j,
2767  r;
2768 
2769  /* Assign default values */
2770  if (portstr == NULL)
2771  portstr = "1812";
2772  if (identifier == NULL)
2773  identifier = "postgresql";
2774 
2775  MemSet(&hint, 0, sizeof(hint));
2776  hint.ai_socktype = SOCK_DGRAM;
2777  hint.ai_family = AF_UNSPEC;
2778  port = atoi(portstr);
2779 
2780  r = pg_getaddrinfo_all(server, portstr, &hint, &serveraddrs);
2781  if (r || !serveraddrs)
2782  {
2783  ereport(LOG,
2784  (errmsg("could not translate RADIUS server name \"%s\" to address: %s",
2785  server, gai_strerror(r))));
2786  if (serveraddrs)
2787  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2788  return STATUS_ERROR;
2789  }
2790  /* XXX: add support for multiple returned addresses? */
2791 
2792  /* Construct RADIUS packet */
2793  packet->code = RADIUS_ACCESS_REQUEST;
2794  packet->length = RADIUS_HEADER_LENGTH;
2795  if (!pg_backend_random((char *) packet->vector, RADIUS_VECTOR_LENGTH))
2796  {
2797  ereport(LOG,
2798  (errmsg("could not generate random encryption vector")));
2799  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2800  return STATUS_ERROR;
2801  }
2802  packet->id = packet->vector[0];
2803  radius_add_attribute(packet, RADIUS_SERVICE_TYPE, (unsigned char *) &service, sizeof(service));
2804  radius_add_attribute(packet, RADIUS_USER_NAME, (unsigned char *) user_name, strlen(user_name));
2805  radius_add_attribute(packet, RADIUS_NAS_IDENTIFIER, (unsigned char *) identifier, strlen(identifier));
2806 
2807  /*
2808  * RADIUS password attributes are calculated as: e[0] = p[0] XOR
2809  * MD5(secret + Request Authenticator) for the first group of 16 octets,
2810  * and then: e[i] = p[i] XOR MD5(secret + e[i-1]) for the following ones
2811  * (if necessary)
2812  */
2813  encryptedpasswordlen = ((strlen(passwd) + RADIUS_VECTOR_LENGTH - 1) / RADIUS_VECTOR_LENGTH) * RADIUS_VECTOR_LENGTH;
2814  cryptvector = palloc(strlen(secret) + RADIUS_VECTOR_LENGTH);
2815  memcpy(cryptvector, secret, strlen(secret));
2816 
2817  /* for the first iteration, we use the Request Authenticator vector */
2818  md5trailer = packet->vector;
2819  for (i = 0; i < encryptedpasswordlen; i += RADIUS_VECTOR_LENGTH)
2820  {
2821  memcpy(cryptvector + strlen(secret), md5trailer, RADIUS_VECTOR_LENGTH);
2822 
2823  /*
2824  * .. and for subsequent iterations the result of the previous XOR
2825  * (calculated below)
2826  */
2827  md5trailer = encryptedpassword + i;
2828 
2829  if (!pg_md5_binary(cryptvector, strlen(secret) + RADIUS_VECTOR_LENGTH, encryptedpassword + i))
2830  {
2831  ereport(LOG,
2832  (errmsg("could not perform MD5 encryption of password")));
2833  pfree(cryptvector);
2834  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2835  return STATUS_ERROR;
2836  }
2837 
2838  for (j = i; j < i + RADIUS_VECTOR_LENGTH; j++)
2839  {
2840  if (j < strlen(passwd))
2841  encryptedpassword[j] = passwd[j] ^ encryptedpassword[j];
2842  else
2843  encryptedpassword[j] = '\0' ^ encryptedpassword[j];
2844  }
2845  }
2846  pfree(cryptvector);
2847 
2848  radius_add_attribute(packet, RADIUS_PASSWORD, encryptedpassword, encryptedpasswordlen);
2849 
2850  /* Length needs to be in network order on the wire */
2851  packetlength = packet->length;
2852  packet->length = htons(packet->length);
2853 
2854  sock = socket(serveraddrs[0].ai_family, SOCK_DGRAM, 0);
2855  if (sock == PGINVALID_SOCKET)
2856  {
2857  ereport(LOG,
2858  (errmsg("could not create RADIUS socket: %m")));
2859  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2860  return STATUS_ERROR;
2861  }
2862 
2863  memset(&localaddr, 0, sizeof(localaddr));
2864 #ifdef HAVE_IPV6
2865  localaddr.sin6_family = serveraddrs[0].ai_family;
2866  localaddr.sin6_addr = in6addr_any;
2867  if (localaddr.sin6_family == AF_INET6)
2868  addrsize = sizeof(struct sockaddr_in6);
2869  else
2870  addrsize = sizeof(struct sockaddr_in);
2871 #else
2872  localaddr.sin_family = serveraddrs[0].ai_family;
2873  localaddr.sin_addr.s_addr = INADDR_ANY;
2874  addrsize = sizeof(struct sockaddr_in);
2875 #endif
2876 
2877  if (bind(sock, (struct sockaddr *) & localaddr, addrsize))
2878  {
2879  ereport(LOG,
2880  (errmsg("could not bind local RADIUS socket: %m")));
2881  closesocket(sock);
2882  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2883  return STATUS_ERROR;
2884  }
2885 
2886  if (sendto(sock, radius_buffer, packetlength, 0,
2887  serveraddrs[0].ai_addr, serveraddrs[0].ai_addrlen) < 0)
2888  {
2889  ereport(LOG,
2890  (errmsg("could not send RADIUS packet: %m")));
2891  closesocket(sock);
2892  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2893  return STATUS_ERROR;
2894  }
2895 
2896  /* Don't need the server address anymore */
2897  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2898 
2899  /*
2900  * Figure out at what time we should time out. We can't just use a single
2901  * call to select() with a timeout, since somebody can be sending invalid
2902  * packets to our port thus causing us to retry in a loop and never time
2903  * out.
2904  *
2905  * XXX: Using WaitLatchOrSocket() and doing a CHECK_FOR_INTERRUPTS() if
2906  * the latch was set would improve the responsiveness to
2907  * timeouts/cancellations.
2908  */
2909  gettimeofday(&endtime, NULL);
2910  endtime.tv_sec += RADIUS_TIMEOUT;
2911 
2912  while (true)
2913  {
2914  struct timeval timeout;
2915  struct timeval now;
2916  int64 timeoutval;
2917 
2918  gettimeofday(&now, NULL);
2919  timeoutval = (endtime.tv_sec * 1000000 + endtime.tv_usec) - (now.tv_sec * 1000000 + now.tv_usec);
2920  if (timeoutval <= 0)
2921  {
2922  ereport(LOG,
2923  (errmsg("timeout waiting for RADIUS response from %s",
2924  server)));
2925  closesocket(sock);
2926  return STATUS_ERROR;
2927  }
2928  timeout.tv_sec = timeoutval / 1000000;
2929  timeout.tv_usec = timeoutval % 1000000;
2930 
2931  FD_ZERO(&fdset);
2932  FD_SET(sock, &fdset);
2933 
2934  r = select(sock + 1, &fdset, NULL, NULL, &timeout);
2935  if (r < 0)
2936  {
2937  if (errno == EINTR)
2938  continue;
2939 
2940  /* Anything else is an actual error */
2941  ereport(LOG,
2942  (errmsg("could not check status on RADIUS socket: %m")));
2943  closesocket(sock);
2944  return STATUS_ERROR;
2945  }
2946  if (r == 0)
2947  {
2948  ereport(LOG,
2949  (errmsg("timeout waiting for RADIUS response from %s",
2950  server)));
2951  closesocket(sock);
2952  return STATUS_ERROR;
2953  }
2954 
2955  /*
2956  * Attempt to read the response packet, and verify the contents.
2957  *
2958  * Any packet that's not actually a RADIUS packet, or otherwise does
2959  * not validate as an explicit reject, is just ignored and we retry
2960  * for another packet (until we reach the timeout). This is to avoid
2961  * the possibility to denial-of-service the login by flooding the
2962  * server with invalid packets on the port that we're expecting the
2963  * RADIUS response on.
2964  */
2965 
2966  addrsize = sizeof(remoteaddr);
2967  packetlength = recvfrom(sock, receive_buffer, RADIUS_BUFFER_SIZE, 0,
2968  (struct sockaddr *) & remoteaddr, &addrsize);
2969  if (packetlength < 0)
2970  {
2971  ereport(LOG,
2972  (errmsg("could not read RADIUS response: %m")));
2973  closesocket(sock);
2974  return STATUS_ERROR;
2975  }
2976 
2977 #ifdef HAVE_IPV6
2978  if (remoteaddr.sin6_port != htons(port))
2979 #else
2980  if (remoteaddr.sin_port != htons(port))
2981 #endif
2982  {
2983 #ifdef HAVE_IPV6
2984  ereport(LOG,
2985  (errmsg("RADIUS response from %s was sent from incorrect port: %d",
2986  server, ntohs(remoteaddr.sin6_port))));
2987 #else
2988  ereport(LOG,
2989  (errmsg("RADIUS response from %s was sent from incorrect port: %d",
2990  server, ntohs(remoteaddr.sin_port))));
2991 #endif
2992  continue;
2993  }
2994 
2995  if (packetlength < RADIUS_HEADER_LENGTH)
2996  {
2997  ereport(LOG,
2998  (errmsg("RADIUS response from %s too short: %d", server, packetlength)));
2999  continue;
3000  }
3001 
3002  if (packetlength != ntohs(receivepacket->length))
3003  {
3004  ereport(LOG,
3005  (errmsg("RADIUS response from %s has corrupt length: %d (actual length %d)",
3006  server, ntohs(receivepacket->length), packetlength)));
3007  continue;
3008  }
3009 
3010  if (packet->id != receivepacket->id)
3011  {
3012  ereport(LOG,
3013  (errmsg("RADIUS response from %s is to a different request: %d (should be %d)",
3014  server, receivepacket->id, packet->id)));
3015  continue;
3016  }
3017 
3018  /*
3019  * Verify the response authenticator, which is calculated as
3020  * MD5(Code+ID+Length+RequestAuthenticator+Attributes+Secret)
3021  */
3022  cryptvector = palloc(packetlength + strlen(secret));
3023 
3024  memcpy(cryptvector, receivepacket, 4); /* code+id+length */
3025  memcpy(cryptvector + 4, packet->vector, RADIUS_VECTOR_LENGTH); /* request
3026  * authenticator, from
3027  * original packet */
3028  if (packetlength > RADIUS_HEADER_LENGTH) /* there may be no
3029  * attributes at all */
3030  memcpy(cryptvector + RADIUS_HEADER_LENGTH, receive_buffer + RADIUS_HEADER_LENGTH, packetlength - RADIUS_HEADER_LENGTH);
3031  memcpy(cryptvector + packetlength, secret, strlen(secret));
3032 
3033  if (!pg_md5_binary(cryptvector,
3034  packetlength + strlen(secret),
3035  encryptedpassword))
3036  {
3037  ereport(LOG,
3038  (errmsg("could not perform MD5 encryption of received packet")));
3039  pfree(cryptvector);
3040  continue;
3041  }
3042  pfree(cryptvector);
3043 
3044  if (memcmp(receivepacket->vector, encryptedpassword, RADIUS_VECTOR_LENGTH) != 0)
3045  {
3046  ereport(LOG,
3047  (errmsg("RADIUS response from %s has incorrect MD5 signature",
3048  server)));
3049  continue;
3050  }
3051 
3052  if (receivepacket->code == RADIUS_ACCESS_ACCEPT)
3053  {
3054  closesocket(sock);
3055  return STATUS_OK;
3056  }
3057  else if (receivepacket->code == RADIUS_ACCESS_REJECT)
3058  {
3059  closesocket(sock);
3060  return STATUS_EOF;
3061  }
3062  else
3063  {
3064  ereport(LOG,
3065  (errmsg("RADIUS response from %s has invalid code (%d) for user \"%s\"",
3066  server, receivepacket->code, user_name)));
3067  continue;
3068  }
3069  } /* while (true) */
3070 }
int ldapscope
Definition: hba.h:84
#define send(s, buf, len, flags)
Definition: win32.h:386
#define RADIUS_PASSWORD
Definition: auth.c:2607
#define calloc(a, b)
Definition: header.h:55
#define connect(s, name, namelen)
Definition: win32.h:383
#define HOSTNAME_LOOKUP_DETAIL(port)
static char password[100]
Definition: streamutil.c:41
Definition: hba.h:30
char * ldapserver
Definition: hba.h:78
#define AUTH_REQ_SSPI
Definition: pqcomm.h:174
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:105
void pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai)
Definition: ip.c:88
Definition: hba.h:38
const struct in6_addr in6addr_any
Definition: mingwcompat.c:22
#define NI_NUMERICHOST
Definition: getaddrinfo.h:80
bool pg_isblank(const char c)
Definition: hba.c:160
int ldapport
Definition: hba.h:79
#define pq_flush()
Definition: libpq.h:39
char * ldapbasedn
Definition: hba.h:83
int pq_peekbyte(void)
Definition: pqcomm.c:1000
static void error(void)
Definition: sql-dyntest.c:147
Definition: hba.h:32
int gid_t
Definition: win32.h:261
int Password_encryption
Definition: user.c:47
char * pamservice
Definition: hba.h:75
int uid_t
Definition: win32.h:260
char * peer_cn
Definition: libpq-be.h:182
static void output(uint64 loop_count)
int getpeereid(int sock, uid_t *uid, gid_t *gid)
Definition: getpeereid.c:35
#define closesocket
Definition: port.h:328
uint16 length
Definition: auth.c:2594
#define AUTH_REQ_OK
Definition: pqcomm.h:165
void ClientAuthentication(Port *port)
Definition: auth.c:339
#define AUTH_REQ_GSS
Definition: pqcomm.h:172
char * pstrdup(const char *in)
Definition: mcxt.c:1077
PasswordType get_password_type(const char *shadow_pass)
Definition: crypt.c:99
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
Definition: hba.h:35
int pg_be_scram_exchange(void *opaq, char *input, int inputlen, char **output, int *outputlen, char **logdetail)
Definition: auth-scram.c:231
bool peer_cert_valid
Definition: libpq-be.h:183
struct sockaddr_storage addr
Definition: pqcomm.h:64
unsigned char uint8
Definition: c.h:266
#define RADIUS_VECTOR_LENGTH
Definition: auth.c:2576
#define gettext_noop(x)
Definition: c.h:139
#define SASL_EXCHANGE_SUCCESS
Definition: scram.h:21
#define socket(af, type, protocol)
Definition: win32.h:379
void(* ClientAuthentication_hook_type)(Port *, int)
Definition: auth.h:26
void proc_exit(int code)
Definition: ipc.c:99
int errcode(int sqlerrcode)
Definition: elog.c:575
Definition: libpq-be.h:116
#define STATUS_ERROR
Definition: c.h:976
#define MemSet(start, val, len)
Definition: c.h:857
#define select(n, r, w, e, timeout)
Definition: win32.h:384
return result
Definition: formatting.c:1618
bool ssl_in_use
Definition: libpq-be.h:181
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define recv(s, buf, len, flags)
Definition: win32.h:385
static int CheckRADIUSAuth(Port *port)
Definition: auth.c:2644
#define LOG
Definition: elog.h:26
#define RADIUS_NAS_IDENTIFIER
Definition: auth.c:2609
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
#define putenv(x)
Definition: win32.h:421
#define AI_NUMERICHOST
Definition: getaddrinfo.h:75
#define DEBUG4
Definition: elog.h:22
uint32 AuthRequest
Definition: pqcomm.h:178
List * radiussecrets
Definition: hba.h:94
#define RADIUS_TIMEOUT
Definition: auth.c:2615
pgsocket sock
Definition: libpq-be.h:118
#define AUTH_REQ_MD5
Definition: pqcomm.h:170
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:88
#define gai_strerror
Definition: getaddrinfo.h:148
signed int int32
Definition: c.h:256
char * ldapsuffix
Definition: hba.h:86
int errdetail_internal(const char *fmt,...)
Definition: elog.c:900
#define RADIUS_HEADER_LENGTH
Definition: auth.c:2577
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
Definition: ip.c:57
#define malloc(a)
Definition: header.h:50
Definition: hba.h:34
Definition: hba.h:31
SockAddr raddr
Definition: libpq-be.h:122
bool am_walsender
Definition: walsender.c:108
#define IDENT_USERNAME_MAX
Definition: auth.c:68
unsigned short uint16
Definition: c.h:267
void pfree(void *pointer)
Definition: mcxt.c:950
#define NI_MAXHOST
Definition: getaddrinfo.h:90
#define ERROR
Definition: elog.h:43
bool pam_use_hostname
Definition: hba.h:76
#define bind(s, addr, addrlen)
Definition: win32.h:380
uint8 attribute
Definition: auth.c:2585
void pq_startmsgread(void)
Definition: pqcomm.c:1191
Definition: hba.h:39
static int CheckPWChallengeAuth(Port *port, char **logdetail)
Definition: auth.c:743
static int CheckSCRAMAuth(Port *port, char *shadow_pass, char **logdetail)
Definition: auth.c:846
#define FATAL
Definition: elog.h:52
#define MAXPGPATH
bool pg_krb_caseins_users
Definition: auth.c:160
char * usermap
Definition: hba.h:74
List * radiusports
Definition: hba.h:98
Definition: hba.h:27
List * radiusservers
Definition: hba.h:92
bool include_realm
Definition: hba.h:89
#define DEBUG2
Definition: elog.h:24
Definition: hba.h:29
char * c
#define RADIUS_USER_NAME
Definition: auth.c:2606
bool pg_backend_random(char *dst, int len)
#define IDENT_PORT
Definition: auth.c:71
static char * buf
Definition: pg_test_fsync.c:65
bool Db_user_namespace
Definition: postmaster.c:240
char * ldapbinddn
Definition: hba.h:80
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define COMMERROR
Definition: elog.h:30
void hba_getauthmethod(hbaPort *port)
Definition: hba.c:2984
char * krb_realm
Definition: hba.h:88
#define NI_MAXSERV
Definition: getaddrinfo.h:93
Definition: type.h:125
#define SCRAM_SHA256_NAME
Definition: scram.h:17
ClientAuthentication_hook_type ClientAuthentication_hook
Definition: auth.c:235
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
char * user_name
Definition: libpq-be.h:137
int pgsocket
Definition: port.h:22
int errdetail_log(const char *fmt,...)
Definition: elog.c:921
int linenumber
Definition: hba.h:63
ACCEPT_TYPE_ARG3 salen
Definition: pqcomm.h:65
#define PG_MAX_AUTH_TOKEN_LENGTH
Definition: auth.c:215
static void sendAuthRequest(Port *port, AuthRequest areq, char *extradata, int extralen)
Definition: auth.c:609
char * ldapbindpasswd
Definition: hba.h:81
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
#define STATUS_OK
Definition: c.h:975
char * ldapprefix
Definition: hba.h:85
void * pg_be_scram_init(const char *username, const char *shadow_pass)
Definition: auth-scram.c:138
static char * recv_password_packet(Port *port)
Definition: auth.c:638
int errcode_for_socket_access(void)
Definition: elog.c:669
SockAddr laddr
Definition: libpq-be.h:121
static int port
Definition: pg_regress.c:89
#define RADIUS_ACCESS_ACCEPT
Definition: auth.c:2602
#define AUTH_REQ_PASSWORD
Definition: pqcomm.h:168
int plain_crypt_verify(const char *role, const char *shadow_pass, const char *client_pass, char **logdetail)
Definition: crypt.c:270
HbaLine * hba
Definition: libpq-be.h:144
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
#define WARNING
Definition: elog.h:40
static int CheckMD5Auth(Port *port, char *shadow_pass, char **logdetail)
Definition: auth.c:809
static int ident_inet(hbaPort *port)
Definition: auth.c:1757
int pq_getmessage(StringInfo s, int maxlen)
Definition: pqcomm.c:1253
Definition: hba.h:33
#define RADIUS_BUFFER_SIZE
Definition: auth.c:2581
#define PGINVALID_SOCKET
Definition: port.h:24
#define EINTR
Definition: win32.h:295
#define RADIUS_AUTHENTICATE_ONLY
Definition: auth.c:2612
List * radiusidentifiers
Definition: hba.h:96
static int CheckPasswordAuth(Port *port, char **logdetail)
Definition: auth.c:711
Definition: hba.h:37
int check_usermap(const char *usermap_name, const char *pg_role, const char *auth_user, bool case_insensitive)
Definition: hba.c:2818
int pq_getbyte(void)
Definition: pqcomm.c:981
PasswordType
Definition: crypt.h:24
#define NI_NUMERICSERV
Definition: getaddrinfo.h:83
#define AUTH_REQ_SASL_CONT
Definition: pqcomm.h:176
#define free(a)
Definition: header.h:65
int ai_protocol
Definition: getaddrinfo.h:105
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
#define RADIUS_ACCESS_REQUEST
Definition: auth.c:2601
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
static int PerformRadiusTransaction(char *server, char *secret, char *portstr, char *identifier, char *user_name, char *passwd)
Definition: auth.c:2736
int ai_socktype
Definition: getaddrinfo.h:104
char * get_role_password(const char *role, char **logdetail)
Definition: crypt.c:39
#define RADIUS_MAX_PASSWORD_LENGTH
Definition: auth.c:2578
static int list_length(const List *l)
Definition: pg_list.h:89
#define RADIUS_SERVICE_TYPE
Definition: auth.c:2608
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:965
bool secure_loaded_verify_locations(void)
Definition: be-secure.c:97
int md5_crypt_verify(const char *role, const char *shadow_pass, const char *client_pass, const char *md5_salt, int md5_salt_len, char **logdetail)
Definition: crypt.c:193
bool ldaptls
Definition: hba.h:77
char * ldapsearchattribute
Definition: hba.h:82
#define PG_MAX_SASL_MESSAGE_LENGTH
Definition: auth.c:223
char * rawline
Definition: hba.h:64
char * pg_krb_server_keyfile
Definition: auth.c:159
#define AUTH_REQ_SASL
Definition: pqcomm.h:175
#define AUTH_REQ_GSS_CONT
Definition: pqcomm.h:173
uint8 id
Definition: auth.c:2593
bool upn_username
Definition: hba.h:91
static char * user
Definition: pg_regress.c:92
void * gss
Definition: libpq-be.h:175
void pq_sendbytes(StringInfo buf, const char *data, int datalen)
Definition: pqformat.c:115
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
void pq_sendint(StringInfo buf, int i, int b)
Definition: pqformat.c:236
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:344
static void auth_failed(Port *port, int status, char *logdetail)
Definition: auth.c:251
int i
const char * strerror(int errnum)
Definition: strerror.c:19
uint8 code
Definition: auth.c:2592
uint8 data[FLEXIBLE_ARRAY_MEMBER]
Definition: auth.c:2587
uint8 vector[RADIUS_VECTOR_LENGTH]
Definition: auth.c:2595
bool clientcert
Definition: hba.h:87
size_t ai_addrlen
Definition: getaddrinfo.h:106
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
#define elog
Definition: elog.h:219
bool pg_md5_binary(const void *buff, size_t len, void *outbuf)
Definition: md5.c:305
#define SASL_EXCHANGE_CONTINUE
Definition: scram.h:20
#define DEBUG5
Definition: elog.h:20
#define STATUS_EOF
Definition: c.h:977
static void radius_add_attribute(radius_packet *packet, uint8 type, const unsigned char *data, int len)
Definition: auth.c:2618
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:224
ProtocolVersion proto
Definition: libpq-be.h:120
#define ERRCODE_INVALID_PASSWORD
Definition: fe-connect.c:97
char * database_name
Definition: libpq-be.h:136
Definition: hba.h:36
#define _(x)
Definition: elog.c:84
bool compat_realm
Definition: hba.h:90
static bool interpret_ident_response(const char *ident_response, char *ident_user)
Definition: auth.c:1669
ProtocolVersion FrontendProtocol
Definition: globals.c:27
Definition: hba.h:40
UserAuth auth_method
Definition: hba.h:72
struct sockaddr * ai_addr
Definition: getaddrinfo.h:107
#define offsetof(type, field)
Definition: c.h:555
#define RADIUS_ACCESS_REJECT
Definition: auth.c:2603
uint8 length
Definition: auth.c:2586
int ai_family
Definition: getaddrinfo.h:103