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-sha-256)
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 and
624  * AUTH_REQ_SASL_FIN, which need not be sent until we are ready for
625  * queries.
626  */
627  if (areq != AUTH_REQ_OK && areq != AUTH_REQ_SASL_FIN)
628  pq_flush();
629 
631 }
632 
633 /*
634  * Collect password response packet from frontend.
635  *
636  * Returns NULL if couldn't get password, else palloc'd string.
637  */
638 static char *
640 {
642 
643  pq_startmsgread();
644  if (PG_PROTOCOL_MAJOR(port->proto) >= 3)
645  {
646  /* Expect 'p' message type */
647  int mtype;
648 
649  mtype = pq_getbyte();
650  if (mtype != 'p')
651  {
652  /*
653  * If the client just disconnects without offering a password,
654  * don't make a log entry. This is legal per protocol spec and in
655  * fact commonly done by psql, so complaining just clutters the
656  * log.
657  */
658  if (mtype != EOF)
660  (errcode(ERRCODE_PROTOCOL_VIOLATION),
661  errmsg("expected password response, got message type %d",
662  mtype)));
663  return NULL; /* EOF or bad message type */
664  }
665  }
666  else
667  {
668  /* For pre-3.0 clients, avoid log entry if they just disconnect */
669  if (pq_peekbyte() == EOF)
670  return NULL; /* EOF */
671  }
672 
673  initStringInfo(&buf);
674  if (pq_getmessage(&buf, 1000)) /* receive password */
675  {
676  /* EOF - pq_getmessage already logged a suitable message */
677  pfree(buf.data);
678  return NULL;
679  }
680 
681  /*
682  * Apply sanity check: password packet length should agree with length of
683  * contained string. Note it is safe to use strlen here because
684  * StringInfo is guaranteed to have an appended '\0'.
685  */
686  if (strlen(buf.data) + 1 != buf.len)
688  (errcode(ERRCODE_PROTOCOL_VIOLATION),
689  errmsg("invalid password packet size")));
690 
691  /* Do not echo password to logs, for security. */
692  elog(DEBUG5, "received password packet");
693 
694  /*
695  * Return the received string. Note we do not attempt to do any
696  * character-set conversion on it; since we don't yet know the client's
697  * encoding, there wouldn't be much point.
698  */
699  return buf.data;
700 }
701 
702 
703 /*----------------------------------------------------------------
704  * Password-based authentication mechanisms
705  *----------------------------------------------------------------
706  */
707 
708 /*
709  * Plaintext password authentication.
710  */
711 static int
712 CheckPasswordAuth(Port *port, char **logdetail)
713 {
714  char *passwd;
715  int result;
716  char *shadow_pass;
717 
719 
720  passwd = recv_password_packet(port);
721  if (passwd == NULL)
722  return STATUS_EOF; /* client wouldn't send password */
723 
724  shadow_pass = get_role_password(port->user_name, logdetail);
725  if (shadow_pass)
726  {
727  result = plain_crypt_verify(port->user_name, shadow_pass, passwd,
728  logdetail);
729  }
730  else
731  result = STATUS_ERROR;
732 
733  if (shadow_pass)
734  pfree(shadow_pass);
735  pfree(passwd);
736 
737  return result;
738 }
739 
740 /*
741  * MD5 and SCRAM authentication.
742  */
743 static int
744 CheckPWChallengeAuth(Port *port, char **logdetail)
745 {
746  int auth_result;
747  char *shadow_pass;
748  PasswordType pwtype;
749 
750  Assert(port->hba->auth_method == uaSCRAM ||
751  port->hba->auth_method == uaMD5);
752 
753  /* First look up the user's password. */
754  shadow_pass = get_role_password(port->user_name, logdetail);
755 
756  /*
757  * If the user does not exist, or has no password or it's expired, we
758  * still go through the motions of authentication, to avoid revealing to
759  * the client that the user didn't exist. If 'md5' is allowed, we choose
760  * whether to use 'md5' or 'scram-sha-256' authentication based on current
761  * password_encryption setting. The idea is that most genuine users
762  * probably have a password of that type, and if we pretend that this user
763  * had a password of that type, too, it "blends in" best.
764  */
765  if (!shadow_pass)
766  pwtype = Password_encryption;
767  else
768  pwtype = get_password_type(shadow_pass);
769 
770  /*
771  * If 'md5' authentication is allowed, decide whether to perform 'md5' or
772  * 'scram-sha-256' authentication based on the type of password the user
773  * has. If it's an MD5 hash, we must do MD5 authentication, and if it's a
774  * SCRAM verifier, we must do SCRAM authentication.
775  *
776  * If MD5 authentication is not allowed, always use SCRAM. If the user
777  * had an MD5 password, CheckSCRAMAuth() will fail.
778  */
779  if (port->hba->auth_method == uaMD5 && pwtype == PASSWORD_TYPE_MD5)
780  auth_result = CheckMD5Auth(port, shadow_pass, logdetail);
781  else
782  auth_result = CheckSCRAMAuth(port, shadow_pass, logdetail);
783 
784  if (shadow_pass)
785  pfree(shadow_pass);
786 
787  /*
788  * If get_role_password() returned error, return error, even if the
789  * authentication succeeded.
790  */
791  if (!shadow_pass)
792  {
793  Assert(auth_result != STATUS_OK);
794  return STATUS_ERROR;
795  }
796  return auth_result;
797 }
798 
799 static int
800 CheckMD5Auth(Port *port, char *shadow_pass, char **logdetail)
801 {
802  char md5Salt[4]; /* Password salt */
803  char *passwd;
804  int result;
805 
806  if (Db_user_namespace)
807  ereport(FATAL,
808  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
809  errmsg("MD5 authentication is not supported when \"db_user_namespace\" is enabled")));
810 
811  /* include the salt to use for computing the response */
812  if (!pg_backend_random(md5Salt, 4))
813  {
814  ereport(LOG,
815  (errmsg("could not generate random MD5 salt")));
816  return STATUS_ERROR;
817  }
818 
819  sendAuthRequest(port, AUTH_REQ_MD5, md5Salt, 4);
820 
821  passwd = recv_password_packet(port);
822  if (passwd == NULL)
823  return STATUS_EOF; /* client wouldn't send password */
824 
825  if (shadow_pass)
826  result = md5_crypt_verify(port->user_name, shadow_pass, passwd,
827  md5Salt, 4, logdetail);
828  else
829  result = STATUS_ERROR;
830 
831  pfree(passwd);
832 
833  return result;
834 }
835 
836 static int
837 CheckSCRAMAuth(Port *port, char *shadow_pass, char **logdetail)
838 {
839  int mtype;
841  void *scram_opaq;
842  char *output = NULL;
843  int outputlen = 0;
844  char *input;
845  int inputlen;
846  int result;
847  bool initial;
848 
849  /*
850  * SASL auth is not supported for protocol versions before 3, because it
851  * relies on the overall message length word to determine the SASL payload
852  * size in AuthenticationSASLContinue and PasswordMessage messages. (We
853  * used to have a hard rule that protocol messages must be parsable
854  * without relying on the length word, but we hardly care about older
855  * protocol version anymore.)
856  */
858  ereport(FATAL,
859  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
860  errmsg("SASL authentication is not supported in protocol version 2")));
861 
862  /*
863  * Send the SASL authentication request to user. It includes the list of
864  * authentication mechanisms (which is trivial, because we only support
865  * SCRAM-SHA-256 at the moment). The extra "\0" is for an empty string to
866  * terminate the list.
867  */
869  strlen(SCRAM_SHA256_NAME) + 2);
870 
871  /*
872  * Initialize the status tracker for message exchanges.
873  *
874  * If the user doesn't exist, or doesn't have a valid password, or it's
875  * expired, we still go through the motions of SASL authentication, but
876  * tell the authentication method that the authentication is "doomed".
877  * That is, it's going to fail, no matter what.
878  *
879  * This is because we don't want to reveal to an attacker what usernames
880  * are valid, nor which users have a valid password.
881  */
882  scram_opaq = pg_be_scram_init(port->user_name, shadow_pass);
883 
884  /*
885  * Loop through SASL message exchange. This exchange can consist of
886  * multiple messages sent in both directions. First message is always
887  * from the client. All messages from client to server are password
888  * packets (type 'p').
889  */
890  initial = true;
891  do
892  {
893  pq_startmsgread();
894  mtype = pq_getbyte();
895  if (mtype != 'p')
896  {
897  /* Only log error if client didn't disconnect. */
898  if (mtype != EOF)
899  {
901  (errcode(ERRCODE_PROTOCOL_VIOLATION),
902  errmsg("expected SASL response, got message type %d",
903  mtype)));
904  return STATUS_ERROR;
905  }
906  else
907  return STATUS_EOF;
908  }
909 
910  /* Get the actual SASL message */
911  initStringInfo(&buf);
913  {
914  /* EOF - pq_getmessage already logged error */
915  pfree(buf.data);
916  return STATUS_ERROR;
917  }
918 
919  elog(DEBUG4, "Processing received SASL response of length %d", buf.len);
920 
921  /*
922  * The first SASLInitialResponse message is different from the others.
923  * It indicates which SASL mechanism the client selected, and contains
924  * an optional Initial Client Response payload. The subsequent
925  * SASLResponse messages contain just the SASL payload.
926  */
927  if (initial)
928  {
929  const char *selected_mech;
930 
931  /*
932  * We only support SCRAM-SHA-256 at the moment, so anything else
933  * is an error.
934  */
935  selected_mech = pq_getmsgrawstring(&buf);
936  if (strcmp(selected_mech, SCRAM_SHA256_NAME) != 0)
937  {
939  (errcode(ERRCODE_PROTOCOL_VIOLATION),
940  errmsg("client selected an invalid SASL authentication mechanism")));
941  pfree(buf.data);
942  return STATUS_ERROR;
943  }
944 
945  inputlen = pq_getmsgint(&buf, 4);
946  if (inputlen == -1)
947  input = NULL;
948  else
949  input = (char *) pq_getmsgbytes(&buf, inputlen);
950 
951  initial = false;
952  }
953  else
954  {
955  inputlen = buf.len;
956  input = (char *) pq_getmsgbytes(&buf, buf.len);
957  }
958  pq_getmsgend(&buf);
959 
960  /*
961  * The StringInfo guarantees that there's a \0 byte after the
962  * response.
963  */
964  Assert(input == NULL || input[inputlen] == '\0');
965 
966  /*
967  * we pass 'logdetail' as NULL when doing a mock authentication,
968  * because we should already have a better error message in that case
969  */
970  result = pg_be_scram_exchange(scram_opaq, input, inputlen,
971  &output, &outputlen,
972  logdetail);
973 
974  /* input buffer no longer used */
975  pfree(buf.data);
976 
977  if (output)
978  {
979  /*
980  * Negotiation generated data to be sent to the client.
981  */
982  elog(DEBUG4, "sending SASL challenge of length %u", outputlen);
983 
984  if (result == SASL_EXCHANGE_SUCCESS)
985  sendAuthRequest(port, AUTH_REQ_SASL_FIN, output, outputlen);
986  else
987  sendAuthRequest(port, AUTH_REQ_SASL_CONT, output, outputlen);
988 
989  pfree(output);
990  }
991  } while (result == SASL_EXCHANGE_CONTINUE);
992 
993  /* Oops, Something bad happened */
994  if (result != SASL_EXCHANGE_SUCCESS)
995  {
996  return STATUS_ERROR;
997  }
998 
999  return STATUS_OK;
1000 }
1001 
1002 
1003 /*----------------------------------------------------------------
1004  * GSSAPI authentication system
1005  *----------------------------------------------------------------
1006  */
1007 #ifdef ENABLE_GSS
1008 
1009 #if defined(WIN32) && !defined(_MSC_VER)
1010 /*
1011  * MIT Kerberos GSSAPI DLL doesn't properly export the symbols for MingW
1012  * that contain the OIDs required. Redefine here, values copied
1013  * from src/athena/auth/krb5/src/lib/gssapi/generic/gssapi_generic.c
1014  */
1015 static const gss_OID_desc GSS_C_NT_USER_NAME_desc =
1016 {10, (void *) "\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x02"};
1017 static GSS_DLLIMP gss_OID GSS_C_NT_USER_NAME = &GSS_C_NT_USER_NAME_desc;
1018 #endif
1019 
1020 
1021 static void
1022 pg_GSS_error(int severity, char *errmsg, OM_uint32 maj_stat, OM_uint32 min_stat)
1023 {
1024  gss_buffer_desc gmsg;
1025  OM_uint32 lmin_s,
1026  msg_ctx;
1027  char msg_major[128],
1028  msg_minor[128];
1029 
1030  /* Fetch major status message */
1031  msg_ctx = 0;
1032  gss_display_status(&lmin_s, maj_stat, GSS_C_GSS_CODE,
1033  GSS_C_NO_OID, &msg_ctx, &gmsg);
1034  strlcpy(msg_major, gmsg.value, sizeof(msg_major));
1035  gss_release_buffer(&lmin_s, &gmsg);
1036 
1037  if (msg_ctx)
1038 
1039  /*
1040  * More than one message available. XXX: Should we loop and read all
1041  * messages? (same below)
1042  */
1043  ereport(WARNING,
1044  (errmsg_internal("incomplete GSS error report")));
1045 
1046  /* Fetch mechanism minor status message */
1047  msg_ctx = 0;
1048  gss_display_status(&lmin_s, min_stat, GSS_C_MECH_CODE,
1049  GSS_C_NO_OID, &msg_ctx, &gmsg);
1050  strlcpy(msg_minor, gmsg.value, sizeof(msg_minor));
1051  gss_release_buffer(&lmin_s, &gmsg);
1052 
1053  if (msg_ctx)
1054  ereport(WARNING,
1055  (errmsg_internal("incomplete GSS minor error report")));
1056 
1057  /*
1058  * errmsg_internal, since translation of the first part must be done
1059  * before calling this function anyway.
1060  */
1061  ereport(severity,
1062  (errmsg_internal("%s", errmsg),
1063  errdetail_internal("%s: %s", msg_major, msg_minor)));
1064 }
1065 
1066 static int
1067 pg_GSS_recvauth(Port *port)
1068 {
1069  OM_uint32 maj_stat,
1070  min_stat,
1071  lmin_s,
1072  gflags;
1073  int mtype;
1074  int ret;
1076  gss_buffer_desc gbuf;
1077 
1078  /*
1079  * GSS auth is not supported for protocol versions before 3, because it
1080  * relies on the overall message length word to determine the GSS payload
1081  * size in AuthenticationGSSContinue and PasswordMessage messages. (This
1082  * is, in fact, a design error in our GSS support, because protocol
1083  * messages are supposed to be parsable without relying on the length
1084  * word; but it's not worth changing it now.)
1085  */
1087  ereport(FATAL,
1088  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1089  errmsg("GSSAPI is not supported in protocol version 2")));
1090 
1091  if (pg_krb_server_keyfile && strlen(pg_krb_server_keyfile) > 0)
1092  {
1093  /*
1094  * Set default Kerberos keytab file for the Krb5 mechanism.
1095  *
1096  * setenv("KRB5_KTNAME", pg_krb_server_keyfile, 0); except setenv()
1097  * not always available.
1098  */
1099  if (getenv("KRB5_KTNAME") == NULL)
1100  {
1101  size_t kt_len = strlen(pg_krb_server_keyfile) + 14;
1102  char *kt_path = malloc(kt_len);
1103 
1104  if (!kt_path ||
1105  snprintf(kt_path, kt_len, "KRB5_KTNAME=%s",
1106  pg_krb_server_keyfile) != kt_len - 2 ||
1107  putenv(kt_path) != 0)
1108  {
1109  ereport(LOG,
1110  (errcode(ERRCODE_OUT_OF_MEMORY),
1111  errmsg("out of memory")));
1112  return STATUS_ERROR;
1113  }
1114  }
1115  }
1116 
1117  /*
1118  * We accept any service principal that's present in our keytab. This
1119  * increases interoperability between kerberos implementations that see
1120  * for example case sensitivity differently, while not really opening up
1121  * any vector of attack.
1122  */
1123  port->gss->cred = GSS_C_NO_CREDENTIAL;
1124 
1125  /*
1126  * Initialize sequence with an empty context
1127  */
1128  port->gss->ctx = GSS_C_NO_CONTEXT;
1129 
1130  /*
1131  * Loop through GSSAPI message exchange. This exchange can consist of
1132  * multiple messages sent in both directions. First message is always from
1133  * the client. All messages from client to server are password packets
1134  * (type 'p').
1135  */
1136  do
1137  {
1138  pq_startmsgread();
1139 
1141 
1142  mtype = pq_getbyte();
1143  if (mtype != 'p')
1144  {
1145  /* Only log error if client didn't disconnect. */
1146  if (mtype != EOF)
1148  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1149  errmsg("expected GSS response, got message type %d",
1150  mtype)));
1151  return STATUS_ERROR;
1152  }
1153 
1154  /* Get the actual GSS token */
1155  initStringInfo(&buf);
1157  {
1158  /* EOF - pq_getmessage already logged error */
1159  pfree(buf.data);
1160  return STATUS_ERROR;
1161  }
1162 
1163  /* Map to GSSAPI style buffer */
1164  gbuf.length = buf.len;
1165  gbuf.value = buf.data;
1166 
1167  elog(DEBUG4, "Processing received GSS token of length %u",
1168  (unsigned int) gbuf.length);
1169 
1170  maj_stat = gss_accept_sec_context(
1171  &min_stat,
1172  &port->gss->ctx,
1173  port->gss->cred,
1174  &gbuf,
1175  GSS_C_NO_CHANNEL_BINDINGS,
1176  &port->gss->name,
1177  NULL,
1178  &port->gss->outbuf,
1179  &gflags,
1180  NULL,
1181  NULL);
1182 
1183  /* gbuf no longer used */
1184  pfree(buf.data);
1185 
1186  elog(DEBUG5, "gss_accept_sec_context major: %d, "
1187  "minor: %d, outlen: %u, outflags: %x",
1188  maj_stat, min_stat,
1189  (unsigned int) port->gss->outbuf.length, gflags);
1190 
1192 
1193  if (port->gss->outbuf.length != 0)
1194  {
1195  /*
1196  * Negotiation generated data to be sent to the client.
1197  */
1198  elog(DEBUG4, "sending GSS response token of length %u",
1199  (unsigned int) port->gss->outbuf.length);
1200 
1202  port->gss->outbuf.value, port->gss->outbuf.length);
1203 
1204  gss_release_buffer(&lmin_s, &port->gss->outbuf);
1205  }
1206 
1207  if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
1208  {
1209  gss_delete_sec_context(&lmin_s, &port->gss->ctx, GSS_C_NO_BUFFER);
1210  pg_GSS_error(ERROR,
1211  gettext_noop("accepting GSS security context failed"),
1212  maj_stat, min_stat);
1213  }
1214 
1215  if (maj_stat == GSS_S_CONTINUE_NEEDED)
1216  elog(DEBUG4, "GSS continue needed");
1217 
1218  } while (maj_stat == GSS_S_CONTINUE_NEEDED);
1219 
1220  if (port->gss->cred != GSS_C_NO_CREDENTIAL)
1221  {
1222  /*
1223  * Release service principal credentials
1224  */
1225  gss_release_cred(&min_stat, &port->gss->cred);
1226  }
1227 
1228  /*
1229  * GSS_S_COMPLETE indicates that authentication is now complete.
1230  *
1231  * Get the name of the user that authenticated, and compare it to the pg
1232  * username that was specified for the connection.
1233  */
1234  maj_stat = gss_display_name(&min_stat, port->gss->name, &gbuf, NULL);
1235  if (maj_stat != GSS_S_COMPLETE)
1236  pg_GSS_error(ERROR,
1237  gettext_noop("retrieving GSS user name failed"),
1238  maj_stat, min_stat);
1239 
1240  /*
1241  * Split the username at the realm separator
1242  */
1243  if (strchr(gbuf.value, '@'))
1244  {
1245  char *cp = strchr(gbuf.value, '@');
1246 
1247  /*
1248  * If we are not going to include the realm in the username that is
1249  * passed to the ident map, destructively modify it here to remove the
1250  * realm. Then advance past the separator to check the realm.
1251  */
1252  if (!port->hba->include_realm)
1253  *cp = '\0';
1254  cp++;
1255 
1256  if (port->hba->krb_realm != NULL && strlen(port->hba->krb_realm))
1257  {
1258  /*
1259  * Match the realm part of the name first
1260  */
1262  ret = pg_strcasecmp(port->hba->krb_realm, cp);
1263  else
1264  ret = strcmp(port->hba->krb_realm, cp);
1265 
1266  if (ret)
1267  {
1268  /* GSS realm does not match */
1269  elog(DEBUG2,
1270  "GSSAPI realm (%s) and configured realm (%s) don't match",
1271  cp, port->hba->krb_realm);
1272  gss_release_buffer(&lmin_s, &gbuf);
1273  return STATUS_ERROR;
1274  }
1275  }
1276  }
1277  else if (port->hba->krb_realm && strlen(port->hba->krb_realm))
1278  {
1279  elog(DEBUG2,
1280  "GSSAPI did not return realm but realm matching was requested");
1281 
1282  gss_release_buffer(&lmin_s, &gbuf);
1283  return STATUS_ERROR;
1284  }
1285 
1286  ret = check_usermap(port->hba->usermap, port->user_name, gbuf.value,
1288 
1289  gss_release_buffer(&lmin_s, &gbuf);
1290 
1291  return ret;
1292 }
1293 #endif /* ENABLE_GSS */
1294 
1295 
1296 /*----------------------------------------------------------------
1297  * SSPI authentication system
1298  *----------------------------------------------------------------
1299  */
1300 #ifdef ENABLE_SSPI
1301 static void
1302 pg_SSPI_error(int severity, const char *errmsg, SECURITY_STATUS r)
1303 {
1304  char sysmsg[256];
1305 
1306  if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
1307  FORMAT_MESSAGE_FROM_SYSTEM,
1308  NULL, r, 0,
1309  sysmsg, sizeof(sysmsg), NULL) == 0)
1310  ereport(severity,
1311  (errmsg_internal("%s", errmsg),
1312  errdetail_internal("SSPI error %x", (unsigned int) r)));
1313  else
1314  ereport(severity,
1315  (errmsg_internal("%s", errmsg),
1316  errdetail_internal("%s (%x)", sysmsg, (unsigned int) r)));
1317 }
1318 
1319 static int
1320 pg_SSPI_recvauth(Port *port)
1321 {
1322  int mtype;
1324  SECURITY_STATUS r;
1325  CredHandle sspicred;
1326  CtxtHandle *sspictx = NULL,
1327  newctx;
1328  TimeStamp expiry;
1329  ULONG contextattr;
1330  SecBufferDesc inbuf;
1331  SecBufferDesc outbuf;
1332  SecBuffer OutBuffers[1];
1333  SecBuffer InBuffers[1];
1334  HANDLE token;
1335  TOKEN_USER *tokenuser;
1336  DWORD retlen;
1337  char accountname[MAXPGPATH];
1338  char domainname[MAXPGPATH];
1339  DWORD accountnamesize = sizeof(accountname);
1340  DWORD domainnamesize = sizeof(domainname);
1341  SID_NAME_USE accountnameuse;
1342  HMODULE secur32;
1343  QUERY_SECURITY_CONTEXT_TOKEN_FN _QuerySecurityContextToken;
1344 
1345  /*
1346  * SSPI auth is not supported for protocol versions before 3, because it
1347  * relies on the overall message length word to determine the SSPI payload
1348  * size in AuthenticationGSSContinue and PasswordMessage messages. (This
1349  * is, in fact, a design error in our SSPI support, because protocol
1350  * messages are supposed to be parsable without relying on the length
1351  * word; but it's not worth changing it now.)
1352  */
1354  ereport(FATAL,
1355  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1356  errmsg("SSPI is not supported in protocol version 2")));
1357 
1358  /*
1359  * Acquire a handle to the server credentials.
1360  */
1361  r = AcquireCredentialsHandle(NULL,
1362  "negotiate",
1363  SECPKG_CRED_INBOUND,
1364  NULL,
1365  NULL,
1366  NULL,
1367  NULL,
1368  &sspicred,
1369  &expiry);
1370  if (r != SEC_E_OK)
1371  pg_SSPI_error(ERROR, _("could not acquire SSPI credentials"), r);
1372 
1373  /*
1374  * Loop through SSPI message exchange. This exchange can consist of
1375  * multiple messages sent in both directions. First message is always from
1376  * the client. All messages from client to server are password packets
1377  * (type 'p').
1378  */
1379  do
1380  {
1381  pq_startmsgread();
1382  mtype = pq_getbyte();
1383  if (mtype != 'p')
1384  {
1385  /* Only log error if client didn't disconnect. */
1386  if (mtype != EOF)
1388  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1389  errmsg("expected SSPI response, got message type %d",
1390  mtype)));
1391  return STATUS_ERROR;
1392  }
1393 
1394  /* Get the actual SSPI token */
1395  initStringInfo(&buf);
1397  {
1398  /* EOF - pq_getmessage already logged error */
1399  pfree(buf.data);
1400  return STATUS_ERROR;
1401  }
1402 
1403  /* Map to SSPI style buffer */
1404  inbuf.ulVersion = SECBUFFER_VERSION;
1405  inbuf.cBuffers = 1;
1406  inbuf.pBuffers = InBuffers;
1407  InBuffers[0].pvBuffer = buf.data;
1408  InBuffers[0].cbBuffer = buf.len;
1409  InBuffers[0].BufferType = SECBUFFER_TOKEN;
1410 
1411  /* Prepare output buffer */
1412  OutBuffers[0].pvBuffer = NULL;
1413  OutBuffers[0].BufferType = SECBUFFER_TOKEN;
1414  OutBuffers[0].cbBuffer = 0;
1415  outbuf.cBuffers = 1;
1416  outbuf.pBuffers = OutBuffers;
1417  outbuf.ulVersion = SECBUFFER_VERSION;
1418 
1419 
1420  elog(DEBUG4, "Processing received SSPI token of length %u",
1421  (unsigned int) buf.len);
1422 
1423  r = AcceptSecurityContext(&sspicred,
1424  sspictx,
1425  &inbuf,
1426  ASC_REQ_ALLOCATE_MEMORY,
1427  SECURITY_NETWORK_DREP,
1428  &newctx,
1429  &outbuf,
1430  &contextattr,
1431  NULL);
1432 
1433  /* input buffer no longer used */
1434  pfree(buf.data);
1435 
1436  if (outbuf.cBuffers > 0 && outbuf.pBuffers[0].cbBuffer > 0)
1437  {
1438  /*
1439  * Negotiation generated data to be sent to the client.
1440  */
1441  elog(DEBUG4, "sending SSPI response token of length %u",
1442  (unsigned int) outbuf.pBuffers[0].cbBuffer);
1443 
1444  port->gss->outbuf.length = outbuf.pBuffers[0].cbBuffer;
1445  port->gss->outbuf.value = outbuf.pBuffers[0].pvBuffer;
1446 
1448  port->gss->outbuf.value, port->gss->outbuf.length);
1449 
1450  FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
1451  }
1452 
1453  if (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)
1454  {
1455  if (sspictx != NULL)
1456  {
1457  DeleteSecurityContext(sspictx);
1458  free(sspictx);
1459  }
1460  FreeCredentialsHandle(&sspicred);
1461  pg_SSPI_error(ERROR,
1462  _("could not accept SSPI security context"), r);
1463  }
1464 
1465  /*
1466  * Overwrite the current context with the one we just received. If
1467  * sspictx is NULL it was the first loop and we need to allocate a
1468  * buffer for it. On subsequent runs, we can just overwrite the buffer
1469  * contents since the size does not change.
1470  */
1471  if (sspictx == NULL)
1472  {
1473  sspictx = malloc(sizeof(CtxtHandle));
1474  if (sspictx == NULL)
1475  ereport(ERROR,
1476  (errmsg("out of memory")));
1477  }
1478 
1479  memcpy(sspictx, &newctx, sizeof(CtxtHandle));
1480 
1481  if (r == SEC_I_CONTINUE_NEEDED)
1482  elog(DEBUG4, "SSPI continue needed");
1483 
1484  } while (r == SEC_I_CONTINUE_NEEDED);
1485 
1486 
1487  /*
1488  * Release service principal credentials
1489  */
1490  FreeCredentialsHandle(&sspicred);
1491 
1492 
1493  /*
1494  * SEC_E_OK indicates that authentication is now complete.
1495  *
1496  * Get the name of the user that authenticated, and compare it to the pg
1497  * username that was specified for the connection.
1498  *
1499  * MingW is missing the export for QuerySecurityContextToken in the
1500  * secur32 library, so we have to load it dynamically.
1501  */
1502 
1503  secur32 = LoadLibrary("SECUR32.DLL");
1504  if (secur32 == NULL)
1505  ereport(ERROR,
1506  (errmsg_internal("could not load secur32.dll: error code %lu",
1507  GetLastError())));
1508 
1509  _QuerySecurityContextToken = (QUERY_SECURITY_CONTEXT_TOKEN_FN)
1510  GetProcAddress(secur32, "QuerySecurityContextToken");
1511  if (_QuerySecurityContextToken == NULL)
1512  {
1513  FreeLibrary(secur32);
1514  ereport(ERROR,
1515  (errmsg_internal("could not locate QuerySecurityContextToken in secur32.dll: error code %lu",
1516  GetLastError())));
1517  }
1518 
1519  r = (_QuerySecurityContextToken) (sspictx, &token);
1520  if (r != SEC_E_OK)
1521  {
1522  FreeLibrary(secur32);
1523  pg_SSPI_error(ERROR,
1524  _("could not get token from SSPI security context"), r);
1525  }
1526 
1527  FreeLibrary(secur32);
1528 
1529  /*
1530  * No longer need the security context, everything from here on uses the
1531  * token instead.
1532  */
1533  DeleteSecurityContext(sspictx);
1534  free(sspictx);
1535 
1536  if (!GetTokenInformation(token, TokenUser, NULL, 0, &retlen) && GetLastError() != 122)
1537  ereport(ERROR,
1538  (errmsg_internal("could not get token information buffer size: error code %lu",
1539  GetLastError())));
1540 
1541  tokenuser = malloc(retlen);
1542  if (tokenuser == NULL)
1543  ereport(ERROR,
1544  (errmsg("out of memory")));
1545 
1546  if (!GetTokenInformation(token, TokenUser, tokenuser, retlen, &retlen))
1547  ereport(ERROR,
1548  (errmsg_internal("could not get token information: error code %lu",
1549  GetLastError())));
1550 
1551  CloseHandle(token);
1552 
1553  if (!LookupAccountSid(NULL, tokenuser->User.Sid, accountname, &accountnamesize,
1554  domainname, &domainnamesize, &accountnameuse))
1555  ereport(ERROR,
1556  (errmsg_internal("could not look up account SID: error code %lu",
1557  GetLastError())));
1558 
1559  free(tokenuser);
1560 
1561  if (!port->hba->compat_realm)
1562  {
1563  int status = pg_SSPI_make_upn(accountname, sizeof(accountname),
1564  domainname, sizeof(domainname),
1565  port->hba->upn_username);
1566 
1567  if (status != STATUS_OK)
1568  /* Error already reported from pg_SSPI_make_upn */
1569  return status;
1570  }
1571 
1572  /*
1573  * Compare realm/domain if requested. In SSPI, always compare case
1574  * insensitive.
1575  */
1576  if (port->hba->krb_realm && strlen(port->hba->krb_realm))
1577  {
1578  if (pg_strcasecmp(port->hba->krb_realm, domainname) != 0)
1579  {
1580  elog(DEBUG2,
1581  "SSPI domain (%s) and configured domain (%s) don't match",
1582  domainname, port->hba->krb_realm);
1583 
1584  return STATUS_ERROR;
1585  }
1586  }
1587 
1588  /*
1589  * We have the username (without domain/realm) in accountname, compare to
1590  * the supplied value. In SSPI, always compare case insensitive.
1591  *
1592  * If set to include realm, append it in <username>@<realm> format.
1593  */
1594  if (port->hba->include_realm)
1595  {
1596  char *namebuf;
1597  int retval;
1598 
1599  namebuf = psprintf("%s@%s", accountname, domainname);
1600  retval = check_usermap(port->hba->usermap, port->user_name, namebuf, true);
1601  pfree(namebuf);
1602  return retval;
1603  }
1604  else
1605  return check_usermap(port->hba->usermap, port->user_name, accountname, true);
1606 }
1607 
1608 /*
1609  * Replaces the domainname with the Kerberos realm name,
1610  * and optionally the accountname with the Kerberos user name.
1611  */
1612 static int
1613 pg_SSPI_make_upn(char *accountname,
1614  size_t accountnamesize,
1615  char *domainname,
1616  size_t domainnamesize,
1617  bool update_accountname)
1618 {
1619  char *samname;
1620  char *upname = NULL;
1621  char *p = NULL;
1622  ULONG upnamesize = 0;
1623  size_t upnamerealmsize;
1624  BOOLEAN res;
1625 
1626  /*
1627  * Build SAM name (DOMAIN\user), then translate to UPN
1628  * (user@kerberos.realm). The realm name is returned in lower case, but
1629  * that is fine because in SSPI auth, string comparisons are always
1630  * case-insensitive.
1631  */
1632 
1633  samname = psprintf("%s\\%s", domainname, accountname);
1634  res = TranslateName(samname, NameSamCompatible, NameUserPrincipal,
1635  NULL, &upnamesize);
1636 
1637  if ((!res && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1638  || upnamesize == 0)
1639  {
1640  pfree(samname);
1641  ereport(LOG,
1642  (errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1643  errmsg("could not translate name")));
1644  return STATUS_ERROR;
1645  }
1646 
1647  /* upnamesize includes the terminating NUL. */
1648  upname = palloc(upnamesize);
1649 
1650  res = TranslateName(samname, NameSamCompatible, NameUserPrincipal,
1651  upname, &upnamesize);
1652 
1653  pfree(samname);
1654  if (res)
1655  p = strchr(upname, '@');
1656 
1657  if (!res || p == NULL)
1658  {
1659  pfree(upname);
1660  ereport(LOG,
1661  (errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1662  errmsg("could not translate name")));
1663  return STATUS_ERROR;
1664  }
1665 
1666  /* Length of realm name after the '@', including the NUL. */
1667  upnamerealmsize = upnamesize - (p - upname + 1);
1668 
1669  /* Replace domainname with realm name. */
1670  if (upnamerealmsize > domainnamesize)
1671  {
1672  pfree(upname);
1673  ereport(LOG,
1674  (errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1675  errmsg("realm name too long")));
1676  return STATUS_ERROR;
1677  }
1678 
1679  /* Length is now safe. */
1680  strcpy(domainname, p + 1);
1681 
1682  /* Replace account name as well (in case UPN != SAM)? */
1683  if (update_accountname)
1684  {
1685  if ((p - upname + 1) > accountnamesize)
1686  {
1687  pfree(upname);
1688  ereport(LOG,
1689  (errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1690  errmsg("translated account name too long")));
1691  return STATUS_ERROR;
1692  }
1693 
1694  *p = 0;
1695  strcpy(accountname, upname);
1696  }
1697 
1698  pfree(upname);
1699  return STATUS_OK;
1700 }
1701 #endif /* ENABLE_SSPI */
1702 
1703 
1704 
1705 /*----------------------------------------------------------------
1706  * Ident authentication system
1707  *----------------------------------------------------------------
1708  */
1709 
1710 /*
1711  * Parse the string "*ident_response" as a response from a query to an Ident
1712  * server. If it's a normal response indicating a user name, return true
1713  * and store the user name at *ident_user. If it's anything else,
1714  * return false.
1715  */
1716 static bool
1717 interpret_ident_response(const char *ident_response,
1718  char *ident_user)
1719 {
1720  const char *cursor = ident_response; /* Cursor into *ident_response */
1721 
1722  /*
1723  * Ident's response, in the telnet tradition, should end in crlf (\r\n).
1724  */
1725  if (strlen(ident_response) < 2)
1726  return false;
1727  else if (ident_response[strlen(ident_response) - 2] != '\r')
1728  return false;
1729  else
1730  {
1731  while (*cursor != ':' && *cursor != '\r')
1732  cursor++; /* skip port field */
1733 
1734  if (*cursor != ':')
1735  return false;
1736  else
1737  {
1738  /* We're positioned to colon before response type field */
1739  char response_type[80];
1740  int i; /* Index into *response_type */
1741 
1742  cursor++; /* Go over colon */
1743  while (pg_isblank(*cursor))
1744  cursor++; /* skip blanks */
1745  i = 0;
1746  while (*cursor != ':' && *cursor != '\r' && !pg_isblank(*cursor) &&
1747  i < (int) (sizeof(response_type) - 1))
1748  response_type[i++] = *cursor++;
1749  response_type[i] = '\0';
1750  while (pg_isblank(*cursor))
1751  cursor++; /* skip blanks */
1752  if (strcmp(response_type, "USERID") != 0)
1753  return false;
1754  else
1755  {
1756  /*
1757  * It's a USERID response. Good. "cursor" should be pointing
1758  * to the colon that precedes the operating system type.
1759  */
1760  if (*cursor != ':')
1761  return false;
1762  else
1763  {
1764  cursor++; /* Go over colon */
1765  /* Skip over operating system field. */
1766  while (*cursor != ':' && *cursor != '\r')
1767  cursor++;
1768  if (*cursor != ':')
1769  return false;
1770  else
1771  {
1772  int i; /* Index into *ident_user */
1773 
1774  cursor++; /* Go over colon */
1775  while (pg_isblank(*cursor))
1776  cursor++; /* skip blanks */
1777  /* Rest of line is user name. Copy it over. */
1778  i = 0;
1779  while (*cursor != '\r' && i < IDENT_USERNAME_MAX)
1780  ident_user[i++] = *cursor++;
1781  ident_user[i] = '\0';
1782  return true;
1783  }
1784  }
1785  }
1786  }
1787  }
1788 }
1789 
1790 
1791 /*
1792  * Talk to the ident server on host "remote_ip_addr" and find out who
1793  * owns the tcp connection from his port "remote_port" to port
1794  * "local_port_addr" on host "local_ip_addr". Return the user name the
1795  * ident server gives as "*ident_user".
1796  *
1797  * IP addresses and port numbers are in network byte order.
1798  *
1799  * But iff we're unable to get the information from ident, return false.
1800  *
1801  * XXX: Using WaitLatchOrSocket() and doing a CHECK_FOR_INTERRUPTS() if the
1802  * latch was set would improve the responsiveness to timeouts/cancellations.
1803  */
1804 static int
1806 {
1807  const SockAddr remote_addr = port->raddr;
1808  const SockAddr local_addr = port->laddr;
1809  char ident_user[IDENT_USERNAME_MAX + 1];
1810  pgsocket sock_fd = PGINVALID_SOCKET; /* for talking to Ident server */
1811  int rc; /* Return code from a locally called function */
1812  bool ident_return;
1813  char remote_addr_s[NI_MAXHOST];
1814  char remote_port[NI_MAXSERV];
1815  char local_addr_s[NI_MAXHOST];
1816  char local_port[NI_MAXSERV];
1817  char ident_port[NI_MAXSERV];
1818  char ident_query[80];
1819  char ident_response[80 + IDENT_USERNAME_MAX];
1820  struct addrinfo *ident_serv = NULL,
1821  *la = NULL,
1822  hints;
1823 
1824  /*
1825  * Might look a little weird to first convert it to text and then back to
1826  * sockaddr, but it's protocol independent.
1827  */
1828  pg_getnameinfo_all(&remote_addr.addr, remote_addr.salen,
1829  remote_addr_s, sizeof(remote_addr_s),
1830  remote_port, sizeof(remote_port),
1832  pg_getnameinfo_all(&local_addr.addr, local_addr.salen,
1833  local_addr_s, sizeof(local_addr_s),
1834  local_port, sizeof(local_port),
1836 
1837  snprintf(ident_port, sizeof(ident_port), "%d", IDENT_PORT);
1838  hints.ai_flags = AI_NUMERICHOST;
1839  hints.ai_family = remote_addr.addr.ss_family;
1840  hints.ai_socktype = SOCK_STREAM;
1841  hints.ai_protocol = 0;
1842  hints.ai_addrlen = 0;
1843  hints.ai_canonname = NULL;
1844  hints.ai_addr = NULL;
1845  hints.ai_next = NULL;
1846  rc = pg_getaddrinfo_all(remote_addr_s, ident_port, &hints, &ident_serv);
1847  if (rc || !ident_serv)
1848  {
1849  /* we don't expect this to happen */
1850  ident_return = false;
1851  goto ident_inet_done;
1852  }
1853 
1854  hints.ai_flags = AI_NUMERICHOST;
1855  hints.ai_family = local_addr.addr.ss_family;
1856  hints.ai_socktype = SOCK_STREAM;
1857  hints.ai_protocol = 0;
1858  hints.ai_addrlen = 0;
1859  hints.ai_canonname = NULL;
1860  hints.ai_addr = NULL;
1861  hints.ai_next = NULL;
1862  rc = pg_getaddrinfo_all(local_addr_s, NULL, &hints, &la);
1863  if (rc || !la)
1864  {
1865  /* we don't expect this to happen */
1866  ident_return = false;
1867  goto ident_inet_done;
1868  }
1869 
1870  sock_fd = socket(ident_serv->ai_family, ident_serv->ai_socktype,
1871  ident_serv->ai_protocol);
1872  if (sock_fd == PGINVALID_SOCKET)
1873  {
1874  ereport(LOG,
1876  errmsg("could not create socket for Ident connection: %m")));
1877  ident_return = false;
1878  goto ident_inet_done;
1879  }
1880 
1881  /*
1882  * Bind to the address which the client originally contacted, otherwise
1883  * the ident server won't be able to match up the right connection. This
1884  * is necessary if the PostgreSQL server is running on an IP alias.
1885  */
1886  rc = bind(sock_fd, la->ai_addr, la->ai_addrlen);
1887  if (rc != 0)
1888  {
1889  ereport(LOG,
1891  errmsg("could not bind to local address \"%s\": %m",
1892  local_addr_s)));
1893  ident_return = false;
1894  goto ident_inet_done;
1895  }
1896 
1897  rc = connect(sock_fd, ident_serv->ai_addr,
1898  ident_serv->ai_addrlen);
1899  if (rc != 0)
1900  {
1901  ereport(LOG,
1903  errmsg("could not connect to Ident server at address \"%s\", port %s: %m",
1904  remote_addr_s, ident_port)));
1905  ident_return = false;
1906  goto ident_inet_done;
1907  }
1908 
1909  /* The query we send to the Ident server */
1910  snprintf(ident_query, sizeof(ident_query), "%s,%s\r\n",
1911  remote_port, local_port);
1912 
1913  /* loop in case send is interrupted */
1914  do
1915  {
1917 
1918  rc = send(sock_fd, ident_query, strlen(ident_query), 0);
1919  } while (rc < 0 && errno == EINTR);
1920 
1921  if (rc < 0)
1922  {
1923  ereport(LOG,
1925  errmsg("could not send query to Ident server at address \"%s\", port %s: %m",
1926  remote_addr_s, ident_port)));
1927  ident_return = false;
1928  goto ident_inet_done;
1929  }
1930 
1931  do
1932  {
1934 
1935  rc = recv(sock_fd, ident_response, sizeof(ident_response) - 1, 0);
1936  } while (rc < 0 && errno == EINTR);
1937 
1938  if (rc < 0)
1939  {
1940  ereport(LOG,
1942  errmsg("could not receive response from Ident server at address \"%s\", port %s: %m",
1943  remote_addr_s, ident_port)));
1944  ident_return = false;
1945  goto ident_inet_done;
1946  }
1947 
1948  ident_response[rc] = '\0';
1949  ident_return = interpret_ident_response(ident_response, ident_user);
1950  if (!ident_return)
1951  ereport(LOG,
1952  (errmsg("invalidly formatted response from Ident server: \"%s\"",
1953  ident_response)));
1954 
1955 ident_inet_done:
1956  if (sock_fd != PGINVALID_SOCKET)
1957  closesocket(sock_fd);
1958  if (ident_serv)
1959  pg_freeaddrinfo_all(remote_addr.addr.ss_family, ident_serv);
1960  if (la)
1961  pg_freeaddrinfo_all(local_addr.addr.ss_family, la);
1962 
1963  if (ident_return)
1964  /* Success! Check the usermap */
1965  return check_usermap(port->hba->usermap, port->user_name, ident_user, false);
1966  return STATUS_ERROR;
1967 }
1968 
1969 /*
1970  * Ask kernel about the credentials of the connecting process,
1971  * determine the symbolic name of the corresponding user, and check
1972  * if valid per the usermap.
1973  *
1974  * Iff authorized, return STATUS_OK, otherwise return STATUS_ERROR.
1975  */
1976 #ifdef HAVE_UNIX_SOCKETS
1977 
1978 static int
1979 auth_peer(hbaPort *port)
1980 {
1981  char ident_user[IDENT_USERNAME_MAX + 1];
1982  uid_t uid;
1983  gid_t gid;
1984  struct passwd *pw;
1985 
1986  if (getpeereid(port->sock, &uid, &gid) != 0)
1987  {
1988  /* Provide special error message if getpeereid is a stub */
1989  if (errno == ENOSYS)
1990  ereport(LOG,
1991  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1992  errmsg("peer authentication is not supported on this platform")));
1993  else
1994  ereport(LOG,
1996  errmsg("could not get peer credentials: %m")));
1997  return STATUS_ERROR;
1998  }
1999 
2000  errno = 0; /* clear errno before call */
2001  pw = getpwuid(uid);
2002  if (!pw)
2003  {
2004  ereport(LOG,
2005  (errmsg("could not look up local user ID %ld: %s",
2006  (long) uid,
2007  errno ? strerror(errno) : _("user does not exist"))));
2008  return STATUS_ERROR;
2009  }
2010 
2011  strlcpy(ident_user, pw->pw_name, IDENT_USERNAME_MAX + 1);
2012 
2013  return check_usermap(port->hba->usermap, port->user_name, ident_user, false);
2014 }
2015 #endif /* HAVE_UNIX_SOCKETS */
2016 
2017 
2018 /*----------------------------------------------------------------
2019  * PAM authentication system
2020  *----------------------------------------------------------------
2021  */
2022 #ifdef USE_PAM
2023 
2024 /*
2025  * PAM conversation function
2026  */
2027 
2028 static int
2029 pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg,
2030  struct pam_response ** resp, void *appdata_ptr)
2031 {
2032  char *passwd;
2033  struct pam_response *reply;
2034  int i;
2035 
2036  if (appdata_ptr)
2037  passwd = (char *) appdata_ptr;
2038  else
2039  {
2040  /*
2041  * Workaround for Solaris 2.6 where the PAM library is broken and does
2042  * not pass appdata_ptr to the conversation routine
2043  */
2044  passwd = pam_passwd;
2045  }
2046 
2047  *resp = NULL; /* in case of error exit */
2048 
2049  if (num_msg <= 0 || num_msg > PAM_MAX_NUM_MSG)
2050  return PAM_CONV_ERR;
2051 
2052  /*
2053  * Explicitly not using palloc here - PAM will free this memory in
2054  * pam_end()
2055  */
2056  if ((reply = calloc(num_msg, sizeof(struct pam_response))) == NULL)
2057  {
2058  ereport(LOG,
2059  (errcode(ERRCODE_OUT_OF_MEMORY),
2060  errmsg("out of memory")));
2061  return PAM_CONV_ERR;
2062  }
2063 
2064  for (i = 0; i < num_msg; i++)
2065  {
2066  switch (msg[i]->msg_style)
2067  {
2068  case PAM_PROMPT_ECHO_OFF:
2069  if (strlen(passwd) == 0)
2070  {
2071  /*
2072  * Password wasn't passed to PAM the first time around -
2073  * let's go ask the client to send a password, which we
2074  * then stuff into PAM.
2075  */
2076  sendAuthRequest(pam_port_cludge, AUTH_REQ_PASSWORD, NULL, 0);
2077  passwd = recv_password_packet(pam_port_cludge);
2078  if (passwd == NULL)
2079  {
2080  /*
2081  * Client didn't want to send password. We
2082  * intentionally do not log anything about this.
2083  */
2084  goto fail;
2085  }
2086  if (strlen(passwd) == 0)
2087  {
2088  ereport(LOG,
2089  (errmsg("empty password returned by client")));
2090  goto fail;
2091  }
2092  }
2093  if ((reply[i].resp = strdup(passwd)) == NULL)
2094  goto fail;
2095  reply[i].resp_retcode = PAM_SUCCESS;
2096  break;
2097  case PAM_ERROR_MSG:
2098  ereport(LOG,
2099  (errmsg("error from underlying PAM layer: %s",
2100  msg[i]->msg)));
2101  /* FALL THROUGH */
2102  case PAM_TEXT_INFO:
2103  /* we don't bother to log TEXT_INFO messages */
2104  if ((reply[i].resp = strdup("")) == NULL)
2105  goto fail;
2106  reply[i].resp_retcode = PAM_SUCCESS;
2107  break;
2108  default:
2109  elog(LOG, "unsupported PAM conversation %d/\"%s\"",
2110  msg[i]->msg_style,
2111  msg[i]->msg ? msg[i]->msg : "(none)");
2112  goto fail;
2113  }
2114  }
2115 
2116  *resp = reply;
2117  return PAM_SUCCESS;
2118 
2119 fail:
2120  /* free up whatever we allocated */
2121  for (i = 0; i < num_msg; i++)
2122  {
2123  if (reply[i].resp != NULL)
2124  free(reply[i].resp);
2125  }
2126  free(reply);
2127 
2128  return PAM_CONV_ERR;
2129 }
2130 
2131 
2132 /*
2133  * Check authentication against PAM.
2134  */
2135 static int
2136 CheckPAMAuth(Port *port, char *user, char *password)
2137 {
2138  int retval;
2139  pam_handle_t *pamh = NULL;
2140  char hostinfo[NI_MAXHOST];
2141 
2142  retval = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2143  hostinfo, sizeof(hostinfo), NULL, 0,
2145  if (retval != 0)
2146  {
2147  ereport(WARNING,
2148  (errmsg_internal("pg_getnameinfo_all() failed: %s",
2149  gai_strerror(retval))));
2150  return STATUS_ERROR;
2151  }
2152 
2153  /*
2154  * We can't entirely rely on PAM to pass through appdata --- it appears
2155  * not to work on at least Solaris 2.6. So use these ugly static
2156  * variables instead.
2157  */
2158  pam_passwd = password;
2159  pam_port_cludge = port;
2160 
2161  /*
2162  * Set the application data portion of the conversation struct. This is
2163  * later used inside the PAM conversation to pass the password to the
2164  * authentication module.
2165  */
2166  pam_passw_conv.appdata_ptr = (char *) password; /* from password above,
2167  * not allocated */
2168 
2169  /* Optionally, one can set the service name in pg_hba.conf */
2170  if (port->hba->pamservice && port->hba->pamservice[0] != '\0')
2171  retval = pam_start(port->hba->pamservice, "pgsql@",
2172  &pam_passw_conv, &pamh);
2173  else
2174  retval = pam_start(PGSQL_PAM_SERVICE, "pgsql@",
2175  &pam_passw_conv, &pamh);
2176 
2177  if (retval != PAM_SUCCESS)
2178  {
2179  ereport(LOG,
2180  (errmsg("could not create PAM authenticator: %s",
2181  pam_strerror(pamh, retval))));
2182  pam_passwd = NULL; /* Unset pam_passwd */
2183  return STATUS_ERROR;
2184  }
2185 
2186  retval = pam_set_item(pamh, PAM_USER, user);
2187 
2188  if (retval != PAM_SUCCESS)
2189  {
2190  ereport(LOG,
2191  (errmsg("pam_set_item(PAM_USER) failed: %s",
2192  pam_strerror(pamh, retval))));
2193  pam_passwd = NULL; /* Unset pam_passwd */
2194  return STATUS_ERROR;
2195  }
2196 
2197  retval = pam_set_item(pamh, PAM_RHOST, hostinfo);
2198 
2199  if (retval != PAM_SUCCESS)
2200  {
2201  ereport(LOG,
2202  (errmsg("pam_set_item(PAM_RHOST) failed: %s",
2203  pam_strerror(pamh, retval))));
2204  pam_passwd = NULL;
2205  return STATUS_ERROR;
2206  }
2207 
2208  retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv);
2209 
2210  if (retval != PAM_SUCCESS)
2211  {
2212  ereport(LOG,
2213  (errmsg("pam_set_item(PAM_CONV) failed: %s",
2214  pam_strerror(pamh, retval))));
2215  pam_passwd = NULL; /* Unset pam_passwd */
2216  return STATUS_ERROR;
2217  }
2218 
2219  retval = pam_authenticate(pamh, 0);
2220 
2221  if (retval != PAM_SUCCESS)
2222  {
2223  ereport(LOG,
2224  (errmsg("pam_authenticate failed: %s",
2225  pam_strerror(pamh, retval))));
2226  pam_passwd = NULL; /* Unset pam_passwd */
2227  return STATUS_ERROR;
2228  }
2229 
2230  retval = pam_acct_mgmt(pamh, 0);
2231 
2232  if (retval != PAM_SUCCESS)
2233  {
2234  ereport(LOG,
2235  (errmsg("pam_acct_mgmt failed: %s",
2236  pam_strerror(pamh, retval))));
2237  pam_passwd = NULL; /* Unset pam_passwd */
2238  return STATUS_ERROR;
2239  }
2240 
2241  retval = pam_end(pamh, retval);
2242 
2243  if (retval != PAM_SUCCESS)
2244  {
2245  ereport(LOG,
2246  (errmsg("could not release PAM authenticator: %s",
2247  pam_strerror(pamh, retval))));
2248  }
2249 
2250  pam_passwd = NULL; /* Unset pam_passwd */
2251 
2252  return (retval == PAM_SUCCESS ? STATUS_OK : STATUS_ERROR);
2253 }
2254 #endif /* USE_PAM */
2255 
2256 
2257 /*----------------------------------------------------------------
2258  * BSD authentication system
2259  *----------------------------------------------------------------
2260  */
2261 #ifdef USE_BSD_AUTH
2262 static int
2263 CheckBSDAuth(Port *port, char *user)
2264 {
2265  char *passwd;
2266  int retval;
2267 
2268  /* Send regular password request to client, and get the response */
2270 
2271  passwd = recv_password_packet(port);
2272  if (passwd == NULL)
2273  return STATUS_EOF;
2274 
2275  /*
2276  * Ask the BSD auth system to verify password. Note that auth_userokay
2277  * will overwrite the password string with zeroes, but it's just a
2278  * temporary string so we don't care.
2279  */
2280  retval = auth_userokay(user, NULL, "auth-postgresql", passwd);
2281 
2282  if (!retval)
2283  return STATUS_ERROR;
2284 
2285  return STATUS_OK;
2286 }
2287 #endif /* USE_BSD_AUTH */
2288 
2289 
2290 /*----------------------------------------------------------------
2291  * LDAP authentication system
2292  *----------------------------------------------------------------
2293  */
2294 #ifdef USE_LDAP
2295 
2296 /*
2297  * Initialize a connection to the LDAP server, including setting up
2298  * TLS if requested.
2299  */
2300 static int
2301 InitializeLDAPConnection(Port *port, LDAP **ldap)
2302 {
2303  int ldapversion = LDAP_VERSION3;
2304  int r;
2305 
2306  *ldap = ldap_init(port->hba->ldapserver, port->hba->ldapport);
2307  if (!*ldap)
2308  {
2309 #ifndef WIN32
2310  ereport(LOG,
2311  (errmsg("could not initialize LDAP: %m")));
2312 #else
2313  ereport(LOG,
2314  (errmsg("could not initialize LDAP: error code %d",
2315  (int) LdapGetLastError())));
2316 #endif
2317  return STATUS_ERROR;
2318  }
2319 
2320  if ((r = ldap_set_option(*ldap, LDAP_OPT_PROTOCOL_VERSION, &ldapversion)) != LDAP_SUCCESS)
2321  {
2322  ldap_unbind(*ldap);
2323  ereport(LOG,
2324  (errmsg("could not set LDAP protocol version: %s", ldap_err2string(r))));
2325  return STATUS_ERROR;
2326  }
2327 
2328  if (port->hba->ldaptls)
2329  {
2330 #ifndef WIN32
2331  if ((r = ldap_start_tls_s(*ldap, NULL, NULL)) != LDAP_SUCCESS)
2332 #else
2333  static __ldap_start_tls_sA _ldap_start_tls_sA = NULL;
2334 
2335  if (_ldap_start_tls_sA == NULL)
2336  {
2337  /*
2338  * Need to load this function dynamically because it does not
2339  * exist on Windows 2000, and causes a load error for the whole
2340  * exe if referenced.
2341  */
2342  HANDLE ldaphandle;
2343 
2344  ldaphandle = LoadLibrary("WLDAP32.DLL");
2345  if (ldaphandle == NULL)
2346  {
2347  /*
2348  * should never happen since we import other files from
2349  * wldap32, but check anyway
2350  */
2351  ldap_unbind(*ldap);
2352  ereport(LOG,
2353  (errmsg("could not load wldap32.dll")));
2354  return STATUS_ERROR;
2355  }
2356  _ldap_start_tls_sA = (__ldap_start_tls_sA) GetProcAddress(ldaphandle, "ldap_start_tls_sA");
2357  if (_ldap_start_tls_sA == NULL)
2358  {
2359  ldap_unbind(*ldap);
2360  ereport(LOG,
2361  (errmsg("could not load function _ldap_start_tls_sA in wldap32.dll"),
2362  errdetail("LDAP over SSL is not supported on this platform.")));
2363  return STATUS_ERROR;
2364  }
2365 
2366  /*
2367  * Leak LDAP handle on purpose, because we need the library to
2368  * stay open. This is ok because it will only ever be leaked once
2369  * per process and is automatically cleaned up on process exit.
2370  */
2371  }
2372  if ((r = _ldap_start_tls_sA(*ldap, NULL, NULL, NULL, NULL)) != LDAP_SUCCESS)
2373 #endif
2374  {
2375  ldap_unbind(*ldap);
2376  ereport(LOG,
2377  (errmsg("could not start LDAP TLS session: %s", ldap_err2string(r))));
2378  return STATUS_ERROR;
2379  }
2380  }
2381 
2382  return STATUS_OK;
2383 }
2384 
2385 /*
2386  * Perform LDAP authentication
2387  */
2388 static int
2389 CheckLDAPAuth(Port *port)
2390 {
2391  char *passwd;
2392  LDAP *ldap;
2393  int r;
2394  char *fulluser;
2395 
2396  if (!port->hba->ldapserver || port->hba->ldapserver[0] == '\0')
2397  {
2398  ereport(LOG,
2399  (errmsg("LDAP server not specified")));
2400  return STATUS_ERROR;
2401  }
2402 
2403  if (port->hba->ldapport == 0)
2404  port->hba->ldapport = LDAP_PORT;
2405 
2407 
2408  passwd = recv_password_packet(port);
2409  if (passwd == NULL)
2410  return STATUS_EOF; /* client wouldn't send password */
2411 
2412  if (strlen(passwd) == 0)
2413  {
2414  ereport(LOG,
2415  (errmsg("empty password returned by client")));
2416  return STATUS_ERROR;
2417  }
2418 
2419  if (InitializeLDAPConnection(port, &ldap) == STATUS_ERROR)
2420  /* Error message already sent */
2421  return STATUS_ERROR;
2422 
2423  if (port->hba->ldapbasedn)
2424  {
2425  /*
2426  * First perform an LDAP search to find the DN for the user we are
2427  * trying to log in as.
2428  */
2429  char *filter;
2430  LDAPMessage *search_message;
2431  LDAPMessage *entry;
2432  char *attributes[2];
2433  char *dn;
2434  char *c;
2435  int count;
2436 
2437  /*
2438  * Disallow any characters that we would otherwise need to escape,
2439  * since they aren't really reasonable in a username anyway. Allowing
2440  * them would make it possible to inject any kind of custom filters in
2441  * the LDAP filter.
2442  */
2443  for (c = port->user_name; *c; c++)
2444  {
2445  if (*c == '*' ||
2446  *c == '(' ||
2447  *c == ')' ||
2448  *c == '\\' ||
2449  *c == '/')
2450  {
2451  ereport(LOG,
2452  (errmsg("invalid character in user name for LDAP authentication")));
2453  return STATUS_ERROR;
2454  }
2455  }
2456 
2457  /*
2458  * Bind with a pre-defined username/password (if available) for
2459  * searching. If none is specified, this turns into an anonymous bind.
2460  */
2461  r = ldap_simple_bind_s(ldap,
2462  port->hba->ldapbinddn ? port->hba->ldapbinddn : "",
2463  port->hba->ldapbindpasswd ? port->hba->ldapbindpasswd : "");
2464  if (r != LDAP_SUCCESS)
2465  {
2466  ereport(LOG,
2467  (errmsg("could not perform initial LDAP bind for ldapbinddn \"%s\" on server \"%s\": %s",
2468  port->hba->ldapbinddn, port->hba->ldapserver, ldap_err2string(r))));
2469  return STATUS_ERROR;
2470  }
2471 
2472  /* Fetch just one attribute, else *all* attributes are returned */
2473  attributes[0] = port->hba->ldapsearchattribute ? port->hba->ldapsearchattribute : "uid";
2474  attributes[1] = NULL;
2475 
2476  filter = psprintf("(%s=%s)",
2477  attributes[0],
2478  port->user_name);
2479 
2480  r = ldap_search_s(ldap,
2481  port->hba->ldapbasedn,
2482  port->hba->ldapscope,
2483  filter,
2484  attributes,
2485  0,
2486  &search_message);
2487 
2488  if (r != LDAP_SUCCESS)
2489  {
2490  ereport(LOG,
2491  (errmsg("could not search LDAP for filter \"%s\" on server \"%s\": %s",
2492  filter, port->hba->ldapserver, ldap_err2string(r))));
2493  pfree(filter);
2494  return STATUS_ERROR;
2495  }
2496 
2497  count = ldap_count_entries(ldap, search_message);
2498  if (count != 1)
2499  {
2500  if (count == 0)
2501  ereport(LOG,
2502  (errmsg("LDAP user \"%s\" does not exist", port->user_name),
2503  errdetail("LDAP search for filter \"%s\" on server \"%s\" returned no entries.",
2504  filter, port->hba->ldapserver)));
2505  else
2506  ereport(LOG,
2507  (errmsg("LDAP user \"%s\" is not unique", port->user_name),
2508  errdetail_plural("LDAP search for filter \"%s\" on server \"%s\" returned %d entry.",
2509  "LDAP search for filter \"%s\" on server \"%s\" returned %d entries.",
2510  count,
2511  filter, port->hba->ldapserver, count)));
2512 
2513  pfree(filter);
2514  ldap_msgfree(search_message);
2515  return STATUS_ERROR;
2516  }
2517 
2518  entry = ldap_first_entry(ldap, search_message);
2519  dn = ldap_get_dn(ldap, entry);
2520  if (dn == NULL)
2521  {
2522  int error;
2523 
2524  (void) ldap_get_option(ldap, LDAP_OPT_ERROR_NUMBER, &error);
2525  ereport(LOG,
2526  (errmsg("could not get dn for the first entry matching \"%s\" on server \"%s\": %s",
2527  filter, port->hba->ldapserver, ldap_err2string(error))));
2528  pfree(filter);
2529  ldap_msgfree(search_message);
2530  return STATUS_ERROR;
2531  }
2532  fulluser = pstrdup(dn);
2533 
2534  pfree(filter);
2535  ldap_memfree(dn);
2536  ldap_msgfree(search_message);
2537 
2538  /* Unbind and disconnect from the LDAP server */
2539  r = ldap_unbind_s(ldap);
2540  if (r != LDAP_SUCCESS)
2541  {
2542  int error;
2543 
2544  (void) ldap_get_option(ldap, LDAP_OPT_ERROR_NUMBER, &error);
2545  ereport(LOG,
2546  (errmsg("could not unbind after searching for user \"%s\" on server \"%s\": %s",
2547  fulluser, port->hba->ldapserver, ldap_err2string(error))));
2548  pfree(fulluser);
2549  return STATUS_ERROR;
2550  }
2551 
2552  /*
2553  * Need to re-initialize the LDAP connection, so that we can bind to
2554  * it with a different username.
2555  */
2556  if (InitializeLDAPConnection(port, &ldap) == STATUS_ERROR)
2557  {
2558  pfree(fulluser);
2559 
2560  /* Error message already sent */
2561  return STATUS_ERROR;
2562  }
2563  }
2564  else
2565  fulluser = psprintf("%s%s%s",
2566  port->hba->ldapprefix ? port->hba->ldapprefix : "",
2567  port->user_name,
2568  port->hba->ldapsuffix ? port->hba->ldapsuffix : "");
2569 
2570  r = ldap_simple_bind_s(ldap, fulluser, passwd);
2571  ldap_unbind(ldap);
2572 
2573  if (r != LDAP_SUCCESS)
2574  {
2575  ereport(LOG,
2576  (errmsg("LDAP login failed for user \"%s\" on server \"%s\": %s",
2577  fulluser, port->hba->ldapserver, ldap_err2string(r))));
2578  pfree(fulluser);
2579  return STATUS_ERROR;
2580  }
2581 
2582  pfree(fulluser);
2583 
2584  return STATUS_OK;
2585 }
2586 #endif /* USE_LDAP */
2587 
2588 
2589 /*----------------------------------------------------------------
2590  * SSL client certificate authentication
2591  *----------------------------------------------------------------
2592  */
2593 #ifdef USE_SSL
2594 static int
2595 CheckCertAuth(Port *port)
2596 {
2597  Assert(port->ssl);
2598 
2599  /* Make sure we have received a username in the certificate */
2600  if (port->peer_cn == NULL ||
2601  strlen(port->peer_cn) <= 0)
2602  {
2603  ereport(LOG,
2604  (errmsg("certificate authentication failed for user \"%s\": client certificate contains no user name",
2605  port->user_name)));
2606  return STATUS_ERROR;
2607  }
2608 
2609  /* Just pass the certificate CN to the usermap check */
2610  return check_usermap(port->hba->usermap, port->user_name, port->peer_cn, false);
2611 }
2612 #endif
2613 
2614 
2615 /*----------------------------------------------------------------
2616  * RADIUS authentication
2617  *----------------------------------------------------------------
2618  */
2619 
2620 /*
2621  * RADIUS authentication is described in RFC2865 (and several others).
2622  */
2623 
2624 #define RADIUS_VECTOR_LENGTH 16
2625 #define RADIUS_HEADER_LENGTH 20
2626 #define RADIUS_MAX_PASSWORD_LENGTH 128
2627 
2628 /* Maximum size of a RADIUS packet we will create or accept */
2629 #define RADIUS_BUFFER_SIZE 1024
2630 
2631 typedef struct
2632 {
2635  uint8 data[FLEXIBLE_ARRAY_MEMBER];
2637 
2638 typedef struct
2639 {
2644  /* this is a bit longer than strictly necessary: */
2646 } radius_packet;
2647 
2648 /* RADIUS packet types */
2649 #define RADIUS_ACCESS_REQUEST 1
2650 #define RADIUS_ACCESS_ACCEPT 2
2651 #define RADIUS_ACCESS_REJECT 3
2652 
2653 /* RAIDUS attributes */
2654 #define RADIUS_USER_NAME 1
2655 #define RADIUS_PASSWORD 2
2656 #define RADIUS_SERVICE_TYPE 6
2657 #define RADIUS_NAS_IDENTIFIER 32
2658 
2659 /* RADIUS service types */
2660 #define RADIUS_AUTHENTICATE_ONLY 8
2661 
2662 /* Seconds to wait - XXX: should be in a config variable! */
2663 #define RADIUS_TIMEOUT 3
2664 
2665 static void
2666 radius_add_attribute(radius_packet *packet, uint8 type, const unsigned char *data, int len)
2667 {
2668  radius_attribute *attr;
2669 
2670  if (packet->length + len > RADIUS_BUFFER_SIZE)
2671  {
2672  /*
2673  * With remotely realistic data, this can never happen. But catch it
2674  * just to make sure we don't overrun a buffer. We'll just skip adding
2675  * the broken attribute, which will in the end cause authentication to
2676  * fail.
2677  */
2678  elog(WARNING,
2679  "Adding attribute code %d with length %d to radius packet would create oversize packet, ignoring",
2680  type, len);
2681  return;
2682  }
2683 
2684  attr = (radius_attribute *) ((unsigned char *) packet + packet->length);
2685  attr->attribute = type;
2686  attr->length = len + 2; /* total size includes type and length */
2687  memcpy(attr->data, data, len);
2688  packet->length += attr->length;
2689 }
2690 
2691 static int
2693 {
2694  char *passwd;
2695  ListCell *server,
2696  *secrets,
2697  *radiusports,
2698  *identifiers;
2699 
2700  /* Make sure struct alignment is correct */
2701  Assert(offsetof(radius_packet, vector) == 4);
2702 
2703  /* Verify parameters */
2704  if (list_length(port->hba->radiusservers) < 1)
2705  {
2706  ereport(LOG,
2707  (errmsg("RADIUS server not specified")));
2708  return STATUS_ERROR;
2709  }
2710 
2711  if (list_length(port->hba->radiussecrets) < 1)
2712  {
2713  ereport(LOG,
2714  (errmsg("RADIUS secret not specified")));
2715  return STATUS_ERROR;
2716  }
2717 
2718  /* Send regular password request to client, and get the response */
2720 
2721  passwd = recv_password_packet(port);
2722  if (passwd == NULL)
2723  return STATUS_EOF; /* client wouldn't send password */
2724 
2725  if (strlen(passwd) == 0)
2726  {
2727  ereport(LOG,
2728  (errmsg("empty password returned by client")));
2729  return STATUS_ERROR;
2730  }
2731 
2732  if (strlen(passwd) > RADIUS_MAX_PASSWORD_LENGTH)
2733  {
2734  ereport(LOG,
2735  (errmsg("RADIUS authentication does not support passwords longer than %d characters", RADIUS_MAX_PASSWORD_LENGTH)));
2736  return STATUS_ERROR;
2737  }
2738 
2739  /*
2740  * Loop over and try each server in order.
2741  */
2742  secrets = list_head(port->hba->radiussecrets);
2743  radiusports = list_head(port->hba->radiusports);
2744  identifiers = list_head(port->hba->radiusidentifiers);
2745  foreach(server, port->hba->radiusservers)
2746  {
2747  int ret = PerformRadiusTransaction(lfirst(server),
2748  lfirst(secrets),
2749  radiusports ? lfirst(radiusports) : NULL,
2750  identifiers ? lfirst(identifiers) : NULL,
2751  port->user_name,
2752  passwd);
2753 
2754  /*------
2755  * STATUS_OK = Login OK
2756  * STATUS_ERROR = Login not OK, but try next server
2757  * STATUS_EOF = Login not OK, and don't try next server
2758  *------
2759  */
2760  if (ret == STATUS_OK)
2761  return STATUS_OK;
2762  else if (ret == STATUS_EOF)
2763  return STATUS_ERROR;
2764 
2765  /*
2766  * secret, port and identifiers either have length 0 (use default),
2767  * length 1 (use the same everywhere) or the same length as servers.
2768  * So if the length is >1, we advance one step. In other cases, we
2769  * don't and will then reuse the correct value.
2770  */
2771  if (list_length(port->hba->radiussecrets) > 1)
2772  secrets = lnext(secrets);
2773  if (list_length(port->hba->radiusports) > 1)
2774  radiusports = lnext(radiusports);
2775  if (list_length(port->hba->radiusidentifiers) > 1)
2776  identifiers = lnext(identifiers);
2777  }
2778 
2779  /* No servers left to try, so give up */
2780  return STATUS_ERROR;
2781 }
2782 
2783 static int
2784 PerformRadiusTransaction(char *server, char *secret, char *portstr, char *identifier, char *user_name, char *passwd)
2785 {
2786  radius_packet radius_send_pack;
2787  radius_packet radius_recv_pack;
2788  radius_packet *packet = &radius_send_pack;
2789  radius_packet *receivepacket = &radius_recv_pack;
2790  char *radius_buffer = (char *) &radius_send_pack;
2791  char *receive_buffer = (char *) &radius_recv_pack;
2792  int32 service = htonl(RADIUS_AUTHENTICATE_ONLY);
2793  uint8 *cryptvector;
2794  int encryptedpasswordlen;
2795  uint8 encryptedpassword[RADIUS_MAX_PASSWORD_LENGTH];
2796  uint8 *md5trailer;
2797  int packetlength;
2798  pgsocket sock;
2799 
2800 #ifdef HAVE_IPV6
2801  struct sockaddr_in6 localaddr;
2802  struct sockaddr_in6 remoteaddr;
2803 #else
2804  struct sockaddr_in localaddr;
2805  struct sockaddr_in remoteaddr;
2806 #endif
2807  struct addrinfo hint;
2808  struct addrinfo *serveraddrs;
2809  int port;
2810  ACCEPT_TYPE_ARG3 addrsize;
2811  fd_set fdset;
2812  struct timeval endtime;
2813  int i,
2814  j,
2815  r;
2816 
2817  /* Assign default values */
2818  if (portstr == NULL)
2819  portstr = "1812";
2820  if (identifier == NULL)
2821  identifier = "postgresql";
2822 
2823  MemSet(&hint, 0, sizeof(hint));
2824  hint.ai_socktype = SOCK_DGRAM;
2825  hint.ai_family = AF_UNSPEC;
2826  port = atoi(portstr);
2827 
2828  r = pg_getaddrinfo_all(server, portstr, &hint, &serveraddrs);
2829  if (r || !serveraddrs)
2830  {
2831  ereport(LOG,
2832  (errmsg("could not translate RADIUS server name \"%s\" to address: %s",
2833  server, gai_strerror(r))));
2834  if (serveraddrs)
2835  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2836  return STATUS_ERROR;
2837  }
2838  /* XXX: add support for multiple returned addresses? */
2839 
2840  /* Construct RADIUS packet */
2841  packet->code = RADIUS_ACCESS_REQUEST;
2842  packet->length = RADIUS_HEADER_LENGTH;
2843  if (!pg_backend_random((char *) packet->vector, RADIUS_VECTOR_LENGTH))
2844  {
2845  ereport(LOG,
2846  (errmsg("could not generate random encryption vector")));
2847  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2848  return STATUS_ERROR;
2849  }
2850  packet->id = packet->vector[0];
2851  radius_add_attribute(packet, RADIUS_SERVICE_TYPE, (unsigned char *) &service, sizeof(service));
2852  radius_add_attribute(packet, RADIUS_USER_NAME, (unsigned char *) user_name, strlen(user_name));
2853  radius_add_attribute(packet, RADIUS_NAS_IDENTIFIER, (unsigned char *) identifier, strlen(identifier));
2854 
2855  /*
2856  * RADIUS password attributes are calculated as: e[0] = p[0] XOR
2857  * MD5(secret + Request Authenticator) for the first group of 16 octets,
2858  * and then: e[i] = p[i] XOR MD5(secret + e[i-1]) for the following ones
2859  * (if necessary)
2860  */
2861  encryptedpasswordlen = ((strlen(passwd) + RADIUS_VECTOR_LENGTH - 1) / RADIUS_VECTOR_LENGTH) * RADIUS_VECTOR_LENGTH;
2862  cryptvector = palloc(strlen(secret) + RADIUS_VECTOR_LENGTH);
2863  memcpy(cryptvector, secret, strlen(secret));
2864 
2865  /* for the first iteration, we use the Request Authenticator vector */
2866  md5trailer = packet->vector;
2867  for (i = 0; i < encryptedpasswordlen; i += RADIUS_VECTOR_LENGTH)
2868  {
2869  memcpy(cryptvector + strlen(secret), md5trailer, RADIUS_VECTOR_LENGTH);
2870 
2871  /*
2872  * .. and for subsequent iterations the result of the previous XOR
2873  * (calculated below)
2874  */
2875  md5trailer = encryptedpassword + i;
2876 
2877  if (!pg_md5_binary(cryptvector, strlen(secret) + RADIUS_VECTOR_LENGTH, encryptedpassword + i))
2878  {
2879  ereport(LOG,
2880  (errmsg("could not perform MD5 encryption of password")));
2881  pfree(cryptvector);
2882  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2883  return STATUS_ERROR;
2884  }
2885 
2886  for (j = i; j < i + RADIUS_VECTOR_LENGTH; j++)
2887  {
2888  if (j < strlen(passwd))
2889  encryptedpassword[j] = passwd[j] ^ encryptedpassword[j];
2890  else
2891  encryptedpassword[j] = '\0' ^ encryptedpassword[j];
2892  }
2893  }
2894  pfree(cryptvector);
2895 
2896  radius_add_attribute(packet, RADIUS_PASSWORD, encryptedpassword, encryptedpasswordlen);
2897 
2898  /* Length needs to be in network order on the wire */
2899  packetlength = packet->length;
2900  packet->length = htons(packet->length);
2901 
2902  sock = socket(serveraddrs[0].ai_family, SOCK_DGRAM, 0);
2903  if (sock == PGINVALID_SOCKET)
2904  {
2905  ereport(LOG,
2906  (errmsg("could not create RADIUS socket: %m")));
2907  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2908  return STATUS_ERROR;
2909  }
2910 
2911  memset(&localaddr, 0, sizeof(localaddr));
2912 #ifdef HAVE_IPV6
2913  localaddr.sin6_family = serveraddrs[0].ai_family;
2914  localaddr.sin6_addr = in6addr_any;
2915  if (localaddr.sin6_family == AF_INET6)
2916  addrsize = sizeof(struct sockaddr_in6);
2917  else
2918  addrsize = sizeof(struct sockaddr_in);
2919 #else
2920  localaddr.sin_family = serveraddrs[0].ai_family;
2921  localaddr.sin_addr.s_addr = INADDR_ANY;
2922  addrsize = sizeof(struct sockaddr_in);
2923 #endif
2924 
2925  if (bind(sock, (struct sockaddr *) & localaddr, addrsize))
2926  {
2927  ereport(LOG,
2928  (errmsg("could not bind local RADIUS socket: %m")));
2929  closesocket(sock);
2930  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2931  return STATUS_ERROR;
2932  }
2933 
2934  if (sendto(sock, radius_buffer, packetlength, 0,
2935  serveraddrs[0].ai_addr, serveraddrs[0].ai_addrlen) < 0)
2936  {
2937  ereport(LOG,
2938  (errmsg("could not send RADIUS packet: %m")));
2939  closesocket(sock);
2940  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2941  return STATUS_ERROR;
2942  }
2943 
2944  /* Don't need the server address anymore */
2945  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2946 
2947  /*
2948  * Figure out at what time we should time out. We can't just use a single
2949  * call to select() with a timeout, since somebody can be sending invalid
2950  * packets to our port thus causing us to retry in a loop and never time
2951  * out.
2952  *
2953  * XXX: Using WaitLatchOrSocket() and doing a CHECK_FOR_INTERRUPTS() if
2954  * the latch was set would improve the responsiveness to
2955  * timeouts/cancellations.
2956  */
2957  gettimeofday(&endtime, NULL);
2958  endtime.tv_sec += RADIUS_TIMEOUT;
2959 
2960  while (true)
2961  {
2962  struct timeval timeout;
2963  struct timeval now;
2964  int64 timeoutval;
2965 
2966  gettimeofday(&now, NULL);
2967  timeoutval = (endtime.tv_sec * 1000000 + endtime.tv_usec) - (now.tv_sec * 1000000 + now.tv_usec);
2968  if (timeoutval <= 0)
2969  {
2970  ereport(LOG,
2971  (errmsg("timeout waiting for RADIUS response from %s",
2972  server)));
2973  closesocket(sock);
2974  return STATUS_ERROR;
2975  }
2976  timeout.tv_sec = timeoutval / 1000000;
2977  timeout.tv_usec = timeoutval % 1000000;
2978 
2979  FD_ZERO(&fdset);
2980  FD_SET(sock, &fdset);
2981 
2982  r = select(sock + 1, &fdset, NULL, NULL, &timeout);
2983  if (r < 0)
2984  {
2985  if (errno == EINTR)
2986  continue;
2987 
2988  /* Anything else is an actual error */
2989  ereport(LOG,
2990  (errmsg("could not check status on RADIUS socket: %m")));
2991  closesocket(sock);
2992  return STATUS_ERROR;
2993  }
2994  if (r == 0)
2995  {
2996  ereport(LOG,
2997  (errmsg("timeout waiting for RADIUS response from %s",
2998  server)));
2999  closesocket(sock);
3000  return STATUS_ERROR;
3001  }
3002 
3003  /*
3004  * Attempt to read the response packet, and verify the contents.
3005  *
3006  * Any packet that's not actually a RADIUS packet, or otherwise does
3007  * not validate as an explicit reject, is just ignored and we retry
3008  * for another packet (until we reach the timeout). This is to avoid
3009  * the possibility to denial-of-service the login by flooding the
3010  * server with invalid packets on the port that we're expecting the
3011  * RADIUS response on.
3012  */
3013 
3014  addrsize = sizeof(remoteaddr);
3015  packetlength = recvfrom(sock, receive_buffer, RADIUS_BUFFER_SIZE, 0,
3016  (struct sockaddr *) & remoteaddr, &addrsize);
3017  if (packetlength < 0)
3018  {
3019  ereport(LOG,
3020  (errmsg("could not read RADIUS response: %m")));
3021  closesocket(sock);
3022  return STATUS_ERROR;
3023  }
3024 
3025 #ifdef HAVE_IPV6
3026  if (remoteaddr.sin6_port != htons(port))
3027 #else
3028  if (remoteaddr.sin_port != htons(port))
3029 #endif
3030  {
3031 #ifdef HAVE_IPV6
3032  ereport(LOG,
3033  (errmsg("RADIUS response from %s was sent from incorrect port: %d",
3034  server, ntohs(remoteaddr.sin6_port))));
3035 #else
3036  ereport(LOG,
3037  (errmsg("RADIUS response from %s was sent from incorrect port: %d",
3038  server, ntohs(remoteaddr.sin_port))));
3039 #endif
3040  continue;
3041  }
3042 
3043  if (packetlength < RADIUS_HEADER_LENGTH)
3044  {
3045  ereport(LOG,
3046  (errmsg("RADIUS response from %s too short: %d", server, packetlength)));
3047  continue;
3048  }
3049 
3050  if (packetlength != ntohs(receivepacket->length))
3051  {
3052  ereport(LOG,
3053  (errmsg("RADIUS response from %s has corrupt length: %d (actual length %d)",
3054  server, ntohs(receivepacket->length), packetlength)));
3055  continue;
3056  }
3057 
3058  if (packet->id != receivepacket->id)
3059  {
3060  ereport(LOG,
3061  (errmsg("RADIUS response from %s is to a different request: %d (should be %d)",
3062  server, receivepacket->id, packet->id)));
3063  continue;
3064  }
3065 
3066  /*
3067  * Verify the response authenticator, which is calculated as
3068  * MD5(Code+ID+Length+RequestAuthenticator+Attributes+Secret)
3069  */
3070  cryptvector = palloc(packetlength + strlen(secret));
3071 
3072  memcpy(cryptvector, receivepacket, 4); /* code+id+length */
3073  memcpy(cryptvector + 4, packet->vector, RADIUS_VECTOR_LENGTH); /* request
3074  * authenticator, from
3075  * original packet */
3076  if (packetlength > RADIUS_HEADER_LENGTH) /* there may be no
3077  * attributes at all */
3078  memcpy(cryptvector + RADIUS_HEADER_LENGTH, receive_buffer + RADIUS_HEADER_LENGTH, packetlength - RADIUS_HEADER_LENGTH);
3079  memcpy(cryptvector + packetlength, secret, strlen(secret));
3080 
3081  if (!pg_md5_binary(cryptvector,
3082  packetlength + strlen(secret),
3083  encryptedpassword))
3084  {
3085  ereport(LOG,
3086  (errmsg("could not perform MD5 encryption of received packet")));
3087  pfree(cryptvector);
3088  continue;
3089  }
3090  pfree(cryptvector);
3091 
3092  if (memcmp(receivepacket->vector, encryptedpassword, RADIUS_VECTOR_LENGTH) != 0)
3093  {
3094  ereport(LOG,
3095  (errmsg("RADIUS response from %s has incorrect MD5 signature",
3096  server)));
3097  continue;
3098  }
3099 
3100  if (receivepacket->code == RADIUS_ACCESS_ACCEPT)
3101  {
3102  closesocket(sock);
3103  return STATUS_OK;
3104  }
3105  else if (receivepacket->code == RADIUS_ACCESS_REJECT)
3106  {
3107  closesocket(sock);
3108  return STATUS_EOF;
3109  }
3110  else
3111  {
3112  ereport(LOG,
3113  (errmsg("RADIUS response from %s has invalid code (%d) for user \"%s\"",
3114  server, receivepacket->code, user_name)));
3115  continue;
3116  }
3117  } /* while (true) */
3118 }
int ldapscope
Definition: hba.h:84
#define send(s, buf, len, flags)
Definition: win32.h:376
#define RADIUS_PASSWORD
Definition: auth.c:2655
#define calloc(a, b)
Definition: header.h:55
#define connect(s, name, namelen)
Definition: win32.h:373
#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:78
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:251
int Password_encryption
Definition: user.c:47
char * pamservice
Definition: hba.h:75
int uid_t
Definition: win32.h:250
#define AUTH_REQ_SASL_FIN
Definition: pqcomm.h:177
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:2642
#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:256
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:2624
#define gettext_noop(x)
Definition: c.h:139
#define SASL_EXCHANGE_SUCCESS
Definition: scram.h:21
#define socket(af, type, protocol)
Definition: win32.h:369
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:374
return result
Definition: formatting.c:1632
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:375
static int CheckRADIUSAuth(Port *port)
Definition: auth.c:2692
#define LOG
Definition: elog.h:26
const char * pq_getmsgrawstring(StringInfo msg)
Definition: pqformat.c:650
#define RADIUS_NAS_IDENTIFIER
Definition: auth.c:2657
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
#define putenv(x)
Definition: win32.h:411
#define AI_NUMERICHOST
Definition: getaddrinfo.h:73
#define DEBUG4
Definition: elog.h:22
uint32 AuthRequest
Definition: pqcomm.h:179
List * radiussecrets
Definition: hba.h:94
#define RADIUS_TIMEOUT
Definition: auth.c:2663
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:146
const char * pq_getmsgbytes(StringInfo msg, int datalen)
Definition: pqformat.c:550
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:2625
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:111
#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:88
#define ERROR
Definition: elog.h:43
bool pam_use_hostname
Definition: hba.h:76
#define bind(s, addr, addrlen)
Definition: win32.h:370
uint8 attribute
Definition: auth.c:2633
void pq_startmsgread(void)
Definition: pqcomm.c:1191
Definition: hba.h:39
static int CheckPWChallengeAuth(Port *port, char **logdetail)
Definition: auth.c:744
static int CheckSCRAMAuth(Port *port, char *shadow_pass, char **logdetail)
Definition: auth.c:837
#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:2654
bool pg_backend_random(char *dst, int len)
#define IDENT_PORT
Definition: auth.c:71
static char * buf
Definition: pg_test_fsync.c:66
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:2987
char * krb_realm
Definition: hba.h:88
#define NI_MAXSERV
Definition: getaddrinfo.h:91
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:171
static char * recv_password_packet(Port *port)
Definition: auth.c:639
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:2650
#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:224
HbaLine * hba
Definition: libpq-be.h:144
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define WARNING
Definition: elog.h:40
static int CheckMD5Auth(Port *port, char *shadow_pass, char **logdetail)
Definition: auth.c:800
static int ident_inet(hbaPort *port)
Definition: auth.c:1805
int pq_getmessage(StringInfo s, int maxlen)
Definition: pqcomm.c:1253
Definition: hba.h:33
#define RADIUS_BUFFER_SIZE
Definition: auth.c:2629
#define PGINVALID_SOCKET
Definition: port.h:24
#define EINTR
Definition: win32.h:285
#define RADIUS_AUTHENTICATE_ONLY
Definition: auth.c:2660
List * radiusidentifiers
Definition: hba.h:96
static int CheckPasswordAuth(Port *port, char **logdetail)
Definition: auth.c:712
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:2821
int pq_getbyte(void)
Definition: pqcomm.c:981
PasswordType
Definition: crypt.h:27
#define NI_NUMERICSERV
Definition: getaddrinfo.h:81
#define AUTH_REQ_SASL_CONT
Definition: pqcomm.h:176
#define free(a)
Definition: header.h:65
int ai_protocol
Definition: getaddrinfo.h:103
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:2649
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:2784
int ai_socktype
Definition: getaddrinfo.h:102
char * get_role_password(const char *role, char **logdetail)
Definition: crypt.c:39
#define RADIUS_MAX_PASSWORD_LENGTH
Definition: auth.c:2626
static int list_length(const List *l)
Definition: pg_list.h:89
#define RADIUS_SERVICE_TYPE
Definition: auth.c:2656
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:168
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:2641
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:2640
uint8 data[FLEXIBLE_ARRAY_MEMBER]
Definition: auth.c:2635
uint8 vector[RADIUS_VECTOR_LENGTH]
Definition: auth.c:2643
bool clientcert
Definition: hba.h:87
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:448
size_t ai_addrlen
Definition: getaddrinfo.h:104
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
#define elog
Definition: elog.h:219
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:677
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:2666
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:93
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:1717
ProtocolVersion FrontendProtocol
Definition: globals.c:27
Definition: hba.h:40
UserAuth auth_method
Definition: hba.h:72
struct sockaddr * ai_addr
Definition: getaddrinfo.h:105
#define offsetof(type, field)
Definition: c.h:555
#define RADIUS_ACCESS_REJECT
Definition: auth.c:2651
uint8 length
Definition: auth.c:2634
int ai_family
Definition: getaddrinfo.h:101