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