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