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