]> granicus.if.org Git - postgresql/blob - src/backend/libpq/auth.c
When a GUC string variable is not set, print the empty string (in SHOW etc.),
[postgresql] / src / backend / libpq / auth.c
1 /*-------------------------------------------------------------------------
2  *
3  * auth.c
4  *        Routines to handle network authentication
5  *
6  * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/libpq/auth.c,v 1.139 2006/07/14 14:52:19 momjian Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "postgres.h"
17
18 #include <sys/param.h>
19 #include <sys/socket.h>
20 #if defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED)
21 #include <sys/uio.h>
22 #include <sys/ucred.h>
23 #endif
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
26
27 #include "libpq/auth.h"
28 #include "libpq/crypt.h"
29 #include "libpq/ip.h"
30 #include "libpq/libpq.h"
31 #include "libpq/pqformat.h"
32 #include "storage/ipc.h"
33
34
35 static void sendAuthRequest(Port *port, AuthRequest areq);
36 static void auth_failed(Port *port, int status);
37 static char *recv_password_packet(Port *port);
38 static int      recv_and_check_password_packet(Port *port);
39
40 char       *pg_krb_server_keyfile;
41 char       *pg_krb_srvnam;
42 bool            pg_krb_caseins_users;
43 char       *pg_krb_server_hostname = NULL;
44
45 #ifdef USE_PAM
46 #ifdef HAVE_PAM_PAM_APPL_H
47 #include <pam/pam_appl.h>
48 #endif
49 #ifdef HAVE_SECURITY_PAM_APPL_H
50 #include <security/pam_appl.h>
51 #endif
52
53 #define PGSQL_PAM_SERVICE "postgresql"  /* Service name passed to PAM */
54
55 static int      CheckPAMAuth(Port *port, char *user, char *password);
56 static int pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg,
57                                          struct pam_response ** resp, void *appdata_ptr);
58
59 static struct pam_conv pam_passw_conv = {
60         &pam_passwd_conv_proc,
61         NULL
62 };
63
64 static char *pam_passwd = NULL; /* Workaround for Solaris 2.6 brokenness */
65 static Port *pam_port_cludge;   /* Workaround for passing "Port *port" into
66                                                                  * pam_passwd_conv_proc */
67 #endif   /* USE_PAM */
68
69 #ifdef USE_LDAP
70 #ifndef WIN32
71 /* We use a deprecated function to keep the codepaths the same as the
72  * win32 one. */
73 #define LDAP_DEPRECATED 1
74 #include <ldap.h>
75 #else
76 /* Header broken in MingW */
77 #define ldap_start_tls_sA __BROKEN_LDAP_HEADER
78 #include <winldap.h>
79 #undef ldap_start_tls_sA
80
81 /* Correct header from the Platform SDK */
82 WINLDAPAPI ULONG ldap_start_tls_sA (
83     IN   PLDAP          ExternalHandle,
84     OUT  PULONG         ServerReturnValue,
85     OUT  LDAPMessage    **result,
86     IN   PLDAPControlA  *ServerControls,
87     IN   PLDAPControlA  *ClientControls
88 );
89 #endif
90
91 static int CheckLDAPAuth(Port *port);
92 #endif
93
94
95 #ifdef KRB5
96 /*----------------------------------------------------------------
97  * MIT Kerberos authentication system - protocol version 5
98  *----------------------------------------------------------------
99  */
100
101 #include <krb5.h>
102 /* Some old versions of Kerberos do not include <com_err.h> in <krb5.h> */
103 #if !defined(__COM_ERR_H) && !defined(__COM_ERR_H__)
104 #include <com_err.h>
105 #endif
106
107 /*
108  * pg_an_to_ln -- return the local name corresponding to an authentication
109  *                                name
110  *
111  * XXX Assumes that the first aname component is the user name.  This is NOT
112  *         necessarily so, since an aname can actually be something out of your
113  *         worst X.400 nightmare, like
114  *                ORGANIZATION=U. C. Berkeley/NAME=Paul M. Aoki@CS.BERKELEY.EDU
115  *         Note that the MIT an_to_ln code does the same thing if you don't
116  *         provide an aname mapping database...it may be a better idea to use
117  *         krb5_an_to_ln, except that it punts if multiple components are found,
118  *         and we can't afford to punt.
119  */
120 static char *
121 pg_an_to_ln(char *aname)
122 {
123         char       *p;
124
125         if ((p = strchr(aname, '/')) || (p = strchr(aname, '@')))
126                 *p = '\0';
127         return aname;
128 }
129
130
131 /*
132  * Various krb5 state which is not connection specfic, and a flag to
133  * indicate whether we have initialised it yet.
134  */
135 static int      pg_krb5_initialised;
136 static krb5_context pg_krb5_context;
137 static krb5_keytab pg_krb5_keytab;
138 static krb5_principal pg_krb5_server;
139
140
141 static int
142 pg_krb5_init(void)
143 {
144         krb5_error_code retval;
145         char       *khostname;
146
147         if (pg_krb5_initialised)
148                 return STATUS_OK;
149
150         retval = krb5_init_context(&pg_krb5_context);
151         if (retval)
152         {
153                 ereport(LOG,
154                                 (errmsg("Kerberos initialization returned error %d",
155                                                 retval)));
156                 com_err("postgres", retval, "while initializing krb5");
157                 return STATUS_ERROR;
158         }
159
160         retval = krb5_kt_resolve(pg_krb5_context, pg_krb_server_keyfile, &pg_krb5_keytab);
161         if (retval)
162         {
163                 ereport(LOG,
164                                 (errmsg("Kerberos keytab resolving returned error %d",
165                                                 retval)));
166                 com_err("postgres", retval, "while resolving keytab file \"%s\"",
167                                 pg_krb_server_keyfile);
168                 krb5_free_context(pg_krb5_context);
169                 return STATUS_ERROR;
170         }
171
172         /*
173          * If no hostname was specified, pg_krb_server_hostname is already NULL.
174          * If it's set to blank, force it to NULL.
175          */
176         khostname = pg_krb_server_hostname;
177         if (khostname && khostname[0] == '\0')
178                 khostname = NULL;
179
180         retval = krb5_sname_to_principal(pg_krb5_context,
181                                                                          khostname,
182                                                                          pg_krb_srvnam,
183                                                                          KRB5_NT_SRV_HST,
184                                                                          &pg_krb5_server);
185         if (retval)
186         {
187                 ereport(LOG,
188                                 (errmsg("Kerberos sname_to_principal(\"%s\", \"%s\") returned error %d",
189                  khostname ? khostname : "server hostname", pg_krb_srvnam, retval)));
190                 com_err("postgres", retval,
191                 "while getting server principal for server \"%s\" for service \"%s\"",
192                                 khostname ? khostname : "server hostname", pg_krb_srvnam);
193                 krb5_kt_close(pg_krb5_context, pg_krb5_keytab);
194                 krb5_free_context(pg_krb5_context);
195                 return STATUS_ERROR;
196         }
197
198         pg_krb5_initialised = 1;
199         return STATUS_OK;
200 }
201
202
203 /*
204  * pg_krb5_recvauth -- server routine to receive authentication information
205  *                                         from the client
206  *
207  * We still need to compare the username obtained from the client's setup
208  * packet to the authenticated name.
209  *
210  * We have our own keytab file because postgres is unlikely to run as root,
211  * and so cannot read the default keytab.
212  */
213 static int
214 pg_krb5_recvauth(Port *port)
215 {
216         krb5_error_code retval;
217         int                     ret;
218         krb5_auth_context auth_context = NULL;
219         krb5_ticket *ticket;
220         char       *kusername;
221
222         ret = pg_krb5_init();
223         if (ret != STATUS_OK)
224                 return ret;
225
226         retval = krb5_recvauth(pg_krb5_context, &auth_context,
227                                                    (krb5_pointer) & port->sock, pg_krb_srvnam,
228                                                    pg_krb5_server, 0, pg_krb5_keytab, &ticket);
229         if (retval)
230         {
231                 ereport(LOG,
232                                 (errmsg("Kerberos recvauth returned error %d",
233                                                 retval)));
234                 com_err("postgres", retval, "from krb5_recvauth");
235                 return STATUS_ERROR;
236         }
237
238         /*
239          * The "client" structure comes out of the ticket and is therefore
240          * authenticated.  Use it to check the username obtained from the
241          * postmaster startup packet.
242          *
243          * I have no idea why this is considered necessary.
244          */
245 #if defined(HAVE_KRB5_TICKET_ENC_PART2)
246         retval = krb5_unparse_name(pg_krb5_context,
247                                                            ticket->enc_part2->client, &kusername);
248 #elif defined(HAVE_KRB5_TICKET_CLIENT)
249         retval = krb5_unparse_name(pg_krb5_context,
250                                                            ticket->client, &kusername);
251 #else
252 #error "bogus configuration"
253 #endif
254         if (retval)
255         {
256                 ereport(LOG,
257                                 (errmsg("Kerberos unparse_name returned error %d",
258                                                 retval)));
259                 com_err("postgres", retval, "while unparsing client name");
260                 krb5_free_ticket(pg_krb5_context, ticket);
261                 krb5_auth_con_free(pg_krb5_context, auth_context);
262                 return STATUS_ERROR;
263         }
264
265         kusername = pg_an_to_ln(kusername);
266         if (pg_krb_caseins_users)
267                 ret = pg_strncasecmp(port->user_name, kusername, SM_DATABASE_USER);
268         else
269                 ret = strncmp(port->user_name, kusername, SM_DATABASE_USER);
270         if (ret)
271         {
272                 ereport(LOG,
273                                 (errmsg("unexpected Kerberos user name received from client (received \"%s\", expected \"%s\")",
274                                                 port->user_name, kusername)));
275                 ret = STATUS_ERROR;
276         }
277         else
278                 ret = STATUS_OK;
279
280         krb5_free_ticket(pg_krb5_context, ticket);
281         krb5_auth_con_free(pg_krb5_context, auth_context);
282         free(kusername);
283
284         return ret;
285 }
286 #else
287
288 static int
289 pg_krb5_recvauth(Port *port)
290 {
291         ereport(LOG,
292                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
293                          errmsg("Kerberos 5 not implemented on this server")));
294         return STATUS_ERROR;
295 }
296 #endif   /* KRB5 */
297
298
299 /*
300  * Tell the user the authentication failed, but not (much about) why.
301  *
302  * There is a tradeoff here between security concerns and making life
303  * unnecessarily difficult for legitimate users.  We would not, for example,
304  * want to report the password we were expecting to receive...
305  * But it seems useful to report the username and authorization method
306  * in use, and these are items that must be presumed known to an attacker
307  * anyway.
308  * Note that many sorts of failure report additional information in the
309  * postmaster log, which we hope is only readable by good guys.
310  */
311 static void
312 auth_failed(Port *port, int status)
313 {
314         const char *errstr;
315
316         /*
317          * If we failed due to EOF from client, just quit; there's no point in
318          * trying to send a message to the client, and not much point in logging
319          * the failure in the postmaster log.  (Logging the failure might be
320          * desirable, were it not for the fact that libpq closes the connection
321          * unceremoniously if challenged for a password when it hasn't got one to
322          * send.  We'll get a useless log entry for every psql connection under
323          * password auth, even if it's perfectly successful, if we log STATUS_EOF
324          * events.)
325          */
326         if (status == STATUS_EOF)
327                 proc_exit(0);
328
329         switch (port->auth_method)
330         {
331                 case uaReject:
332                         errstr = gettext_noop("authentication failed for user \"%s\": host rejected");
333                         break;
334                 case uaKrb5:
335                         errstr = gettext_noop("Kerberos 5 authentication failed for user \"%s\"");
336                         break;
337                 case uaTrust:
338                         errstr = gettext_noop("\"trust\" authentication failed for user \"%s\"");
339                         break;
340                 case uaIdent:
341                         errstr = gettext_noop("Ident authentication failed for user \"%s\"");
342                         break;
343                 case uaMD5:
344                 case uaCrypt:
345                 case uaPassword:
346                         errstr = gettext_noop("password authentication failed for user \"%s\"");
347                         break;
348 #ifdef USE_PAM
349                 case uaPAM:
350                         errstr = gettext_noop("PAM authentication failed for user \"%s\"");
351                         break;
352 #endif   /* USE_PAM */
353 #ifdef USE_LDAP
354         case uaLDAP:
355             errstr = gettext_noop("LDAP authentication failed for user \"%s\"");
356             break;
357 #endif   /* USE_LDAP */
358                 default:
359                         errstr = gettext_noop("authentication failed for user \"%s\": invalid authentication method");
360                         break;
361         }
362
363         ereport(FATAL,
364                         (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
365                          errmsg(errstr, port->user_name)));
366         /* doesn't return */
367 }
368
369
370 /*
371  * Client authentication starts here.  If there is an error, this
372  * function does not return and the backend process is terminated.
373  */
374 void
375 ClientAuthentication(Port *port)
376 {
377         int                     status = STATUS_ERROR;
378
379         /*
380          * Get the authentication method to use for this frontend/database
381          * combination.  Note: a failure return indicates a problem with the hba
382          * config file, not with the request.  hba.c should have dropped an error
383          * message into the postmaster logfile if it failed.
384          */
385         if (hba_getauthmethod(port) != STATUS_OK)
386                 ereport(FATAL,
387                                 (errcode(ERRCODE_CONFIG_FILE_ERROR),
388                                  errmsg("missing or erroneous pg_hba.conf file"),
389                                  errhint("See server log for details.")));
390
391         switch (port->auth_method)
392         {
393                 case uaReject:
394
395                         /*
396                          * This could have come from an explicit "reject" entry in
397                          * pg_hba.conf, but more likely it means there was no matching
398                          * entry.  Take pity on the poor user and issue a helpful error
399                          * message.  NOTE: this is not a security breach, because all the
400                          * info reported here is known at the frontend and must be assumed
401                          * known to bad guys. We're merely helping out the less clueful
402                          * good guys.
403                          */
404                         {
405                                 char            hostinfo[NI_MAXHOST];
406
407                                 pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
408                                                                    hostinfo, sizeof(hostinfo),
409                                                                    NULL, 0,
410                                                                    NI_NUMERICHOST);
411
412 #ifdef USE_SSL
413                                 ereport(FATAL,
414                                                 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
415                                                  errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\", %s",
416                                                           hostinfo, port->user_name, port->database_name,
417                                                                 port->ssl ? _("SSL on") : _("SSL off"))));
418 #else
419                                 ereport(FATAL,
420                                                 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
421                                                  errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\"",
422                                                    hostinfo, port->user_name, port->database_name)));
423 #endif
424                                 break;
425                         }
426
427                 case uaKrb5:
428                         sendAuthRequest(port, AUTH_REQ_KRB5);
429                         status = pg_krb5_recvauth(port);
430                         break;
431
432                 case uaIdent:
433
434                         /*
435                          * If we are doing ident on unix-domain sockets, use SCM_CREDS
436                          * only if it is defined and SO_PEERCRED isn't.
437                          */
438 #if !defined(HAVE_GETPEEREID) && !defined(SO_PEERCRED) && \
439         (defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || \
440          (defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS)))
441                         if (port->raddr.addr.ss_family == AF_UNIX)
442                         {
443 #if defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED)
444
445                                 /*
446                                  * Receive credentials on next message receipt, BSD/OS,
447                                  * NetBSD. We need to set this before the client sends the
448                                  * next packet.
449                                  */
450                                 int                     on = 1;
451
452                                 if (setsockopt(port->sock, 0, LOCAL_CREDS, &on, sizeof(on)) < 0)
453                                         ereport(FATAL,
454                                                         (errcode_for_socket_access(),
455                                            errmsg("could not enable credential reception: %m")));
456 #endif
457
458                                 sendAuthRequest(port, AUTH_REQ_SCM_CREDS);
459                         }
460 #endif
461                         status = authident(port);
462                         break;
463
464                 case uaMD5:
465                         sendAuthRequest(port, AUTH_REQ_MD5);
466                         status = recv_and_check_password_packet(port);
467                         break;
468
469                 case uaCrypt:
470                         sendAuthRequest(port, AUTH_REQ_CRYPT);
471                         status = recv_and_check_password_packet(port);
472                         break;
473
474                 case uaPassword:
475                         sendAuthRequest(port, AUTH_REQ_PASSWORD);
476                         status = recv_and_check_password_packet(port);
477                         break;
478
479 #ifdef USE_PAM
480                 case uaPAM:
481                         pam_port_cludge = port;
482                         status = CheckPAMAuth(port, port->user_name, "");
483                         break;
484 #endif   /* USE_PAM */
485
486 #ifdef USE_LDAP
487         case uaLDAP:
488             status = CheckLDAPAuth(port);
489             break;
490 #endif
491
492                 case uaTrust:
493                         status = STATUS_OK;
494                         break;
495         }
496
497         if (status == STATUS_OK)
498                 sendAuthRequest(port, AUTH_REQ_OK);
499         else
500                 auth_failed(port, status);
501 }
502
503
504 /*
505  * Send an authentication request packet to the frontend.
506  */
507 static void
508 sendAuthRequest(Port *port, AuthRequest areq)
509 {
510         StringInfoData buf;
511
512         pq_beginmessage(&buf, 'R');
513         pq_sendint(&buf, (int32) areq, sizeof(int32));
514
515         /* Add the salt for encrypted passwords. */
516         if (areq == AUTH_REQ_MD5)
517                 pq_sendbytes(&buf, port->md5Salt, 4);
518         else if (areq == AUTH_REQ_CRYPT)
519                 pq_sendbytes(&buf, port->cryptSalt, 2);
520
521         pq_endmessage(&buf);
522
523         /*
524          * Flush message so client will see it, except for AUTH_REQ_OK, which need
525          * not be sent until we are ready for queries.
526          */
527         if (areq != AUTH_REQ_OK)
528                 pq_flush();
529 }
530
531
532 #ifdef USE_PAM
533
534 /*
535  * PAM conversation function
536  */
537
538 static int
539 pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg,
540                                          struct pam_response ** resp, void *appdata_ptr)
541 {
542         if (num_msg != 1 || msg[0]->msg_style != PAM_PROMPT_ECHO_OFF)
543         {
544                 switch (msg[0]->msg_style)
545                 {
546                         case PAM_ERROR_MSG:
547                                 ereport(LOG,
548                                                 (errmsg("error from underlying PAM layer: %s",
549                                                                 msg[0]->msg)));
550                                 return PAM_CONV_ERR;
551                         default:
552                                 ereport(LOG,
553                                                 (errmsg("unsupported PAM conversation %d/%s",
554                                                                 msg[0]->msg_style, msg[0]->msg)));
555                                 return PAM_CONV_ERR;
556                 }
557         }
558
559         if (!appdata_ptr)
560         {
561                 /*
562                  * Workaround for Solaris 2.6 where the PAM library is broken and does
563                  * not pass appdata_ptr to the conversation routine
564                  */
565                 appdata_ptr = pam_passwd;
566         }
567
568         /*
569          * Password wasn't passed to PAM the first time around - let's go ask the
570          * client to send a password, which we then stuff into PAM.
571          */
572         if (strlen(appdata_ptr) == 0)
573         {
574                 char       *passwd;
575
576                 sendAuthRequest(pam_port_cludge, AUTH_REQ_PASSWORD);
577                 passwd = recv_password_packet(pam_port_cludge);
578
579                 if (passwd == NULL)
580                         return PAM_CONV_ERR;    /* client didn't want to send password */
581
582                 if (strlen(passwd) == 0)
583                 {
584                         ereport(LOG,
585                                         (errmsg("empty password returned by client")));
586                         return PAM_CONV_ERR;
587                 }
588                 appdata_ptr = passwd;
589         }
590
591         /*
592          * Explicitly not using palloc here - PAM will free this memory in
593          * pam_end()
594          */
595         *resp = calloc(num_msg, sizeof(struct pam_response));
596         if (!*resp)
597         {
598                 ereport(LOG,
599                                 (errcode(ERRCODE_OUT_OF_MEMORY),
600                                  errmsg("out of memory")));
601                 return PAM_CONV_ERR;
602         }
603
604         (*resp)[0].resp = strdup((char *) appdata_ptr);
605         (*resp)[0].resp_retcode = 0;
606
607         return ((*resp)[0].resp ? PAM_SUCCESS : PAM_CONV_ERR);
608 }
609
610
611 /*
612  * Check authentication against PAM.
613  */
614 static int
615 CheckPAMAuth(Port *port, char *user, char *password)
616 {
617         int                     retval;
618         pam_handle_t *pamh = NULL;
619
620         /*
621          * Apparently, Solaris 2.6 is broken, and needs ugly static variable
622          * workaround
623          */
624         pam_passwd = password;
625
626         /*
627          * Set the application data portion of the conversation struct This is
628          * later used inside the PAM conversation to pass the password to the
629          * authentication module.
630          */
631         pam_passw_conv.appdata_ptr = (char *) password;         /* from password above,
632                                                                                                                  * not allocated */
633
634         /* Optionally, one can set the service name in pg_hba.conf */
635         if (port->auth_arg && port->auth_arg[0] != '\0')
636                 retval = pam_start(port->auth_arg, "pgsql@",
637                                                    &pam_passw_conv, &pamh);
638         else
639                 retval = pam_start(PGSQL_PAM_SERVICE, "pgsql@",
640                                                    &pam_passw_conv, &pamh);
641
642         if (retval != PAM_SUCCESS)
643         {
644                 ereport(LOG,
645                                 (errmsg("could not create PAM authenticator: %s",
646                                                 pam_strerror(pamh, retval))));
647                 pam_passwd = NULL;              /* Unset pam_passwd */
648                 return STATUS_ERROR;
649         }
650
651         retval = pam_set_item(pamh, PAM_USER, user);
652
653         if (retval != PAM_SUCCESS)
654         {
655                 ereport(LOG,
656                                 (errmsg("pam_set_item(PAM_USER) failed: %s",
657                                                 pam_strerror(pamh, retval))));
658                 pam_passwd = NULL;              /* Unset pam_passwd */
659                 return STATUS_ERROR;
660         }
661
662         retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv);
663
664         if (retval != PAM_SUCCESS)
665         {
666                 ereport(LOG,
667                                 (errmsg("pam_set_item(PAM_CONV) failed: %s",
668                                                 pam_strerror(pamh, retval))));
669                 pam_passwd = NULL;              /* Unset pam_passwd */
670                 return STATUS_ERROR;
671         }
672
673         retval = pam_authenticate(pamh, 0);
674
675         if (retval != PAM_SUCCESS)
676         {
677                 ereport(LOG,
678                                 (errmsg("pam_authenticate failed: %s",
679                                                 pam_strerror(pamh, retval))));
680                 pam_passwd = NULL;              /* Unset pam_passwd */
681                 return STATUS_ERROR;
682         }
683
684         retval = pam_acct_mgmt(pamh, 0);
685
686         if (retval != PAM_SUCCESS)
687         {
688                 ereport(LOG,
689                                 (errmsg("pam_acct_mgmt failed: %s",
690                                                 pam_strerror(pamh, retval))));
691                 pam_passwd = NULL;              /* Unset pam_passwd */
692                 return STATUS_ERROR;
693         }
694
695         retval = pam_end(pamh, retval);
696
697         if (retval != PAM_SUCCESS)
698         {
699                 ereport(LOG,
700                                 (errmsg("could not release PAM authenticator: %s",
701                                                 pam_strerror(pamh, retval))));
702         }
703
704         pam_passwd = NULL;                      /* Unset pam_passwd */
705
706         return (retval == PAM_SUCCESS ? STATUS_OK : STATUS_ERROR);
707 }
708 #endif   /* USE_PAM */
709
710
711 #ifdef USE_LDAP
712
713 static int
714 CheckLDAPAuth(Port *port)
715 {
716     char *passwd;
717     char server[128];
718     char basedn[128];
719     char prefix[128];
720     char suffix[128];
721     LDAP *ldap;
722     int  ssl = 0;
723     int  r;
724     int  ldapversion = LDAP_VERSION3;
725     int  ldapport = LDAP_PORT;
726     char fulluser[128];
727
728     if (!port->auth_arg || port->auth_arg[0] == '\0')
729     {
730         ereport(LOG,
731                 (errmsg("LDAP configuration URL not specified")));
732         return STATUS_ERROR;
733     }
734
735     /* 
736      * Crack the LDAP url. We do a very trivial parse..
737      * ldap[s]://<server>[:<port>]/<basedn>[;prefix[;suffix]]
738      */
739
740     server[0] = '\0';
741     basedn[0] = '\0';
742     prefix[0] = '\0';
743     suffix[0] = '\0';
744
745     /* ldap, including port number */
746     r = sscanf(port->auth_arg, 
747             "ldap://%127[^:]:%i/%127[^;];%127[^;];%127s",
748             server, &ldapport, basedn, prefix, suffix);
749     if (r < 3)
750     {
751         /* ldaps, including port number */
752         r = sscanf(port->auth_arg,
753                 "ldaps://%127[^:]:%i/%127[^;];%127[^;];%127s",
754                 server, &ldapport, basedn, prefix, suffix);
755         if (r >=3) ssl = 1;
756     }
757     if (r < 3)
758     {
759         /* ldap, no port number */
760         r = sscanf(port->auth_arg,
761                 "ldap://%127[^/]/%127[^;];%127[^;];%127s",
762                 server, basedn, prefix, suffix);
763     }
764     if (r < 2)
765     {
766         /* ldaps, no port number */
767         r = sscanf(port->auth_arg,
768                 "ldaps://%127[^/]/%127[^;];%127[^;];%127s",
769                 server, basedn, prefix, suffix);
770         if (r >= 2) ssl = 1;
771     }
772     if (r < 2)
773     {
774         ereport(LOG,
775                 (errmsg("invalid LDAP URL: \"%s\"",
776                                                 port->auth_arg)));
777         return STATUS_ERROR;
778     }
779
780     sendAuthRequest(port, AUTH_REQ_PASSWORD);
781     
782     passwd = recv_password_packet(port);
783     if (passwd == NULL)
784         return STATUS_EOF; /* client wouldn't send password */
785    
786     ldap = ldap_init(server, ldapport);
787     if (!ldap)
788     {
789 #ifndef WIN32
790         ereport(LOG,
791                 (errmsg("could not initialize LDAP: error %d", 
792                         errno)));
793 #else
794         ereport(LOG,
795                 (errmsg("could not initialize LDAP: error %d", 
796                         (int) LdapGetLastError())));
797 #endif
798         return STATUS_ERROR;
799     }
800
801     if ((r = ldap_set_option(ldap, LDAP_OPT_PROTOCOL_VERSION, &ldapversion)) != LDAP_SUCCESS)
802     {
803         ereport(LOG,
804                 (errmsg("could not set LDAP protocol version: error %d", r)));
805         return STATUS_ERROR;
806     }
807     
808     if (ssl)
809     {
810 #ifndef WIN32
811         if ((r = ldap_start_tls_s(ldap, NULL, NULL)) != LDAP_SUCCESS)
812 #else
813         if ((r = ldap_start_tls_sA(ldap, NULL, NULL, NULL, NULL)) != LDAP_SUCCESS) 
814 #endif
815         {
816             ereport(LOG,
817                     (errmsg("could not start LDAP TLS session: error %d", r)));
818             return STATUS_ERROR;
819         }
820     }
821
822     snprintf(fulluser, sizeof(fulluser)-1, "%s%s%s",
823                          prefix, port->user_name, suffix);
824     fulluser[sizeof(fulluser)-1] = '\0';
825
826     r = ldap_simple_bind_s(ldap, fulluser, passwd);
827     ldap_unbind(ldap);
828
829     if (r != LDAP_SUCCESS)
830     {
831         ereport(LOG,
832                 (errmsg("LDAP login failed for user \"%s\" on server \"%s\": error %d",
833                                                 fulluser, server, r)));
834         return STATUS_ERROR;
835     }
836     
837     return STATUS_OK;
838 }
839
840 #endif   /* USE_LDAP */
841
842 /*
843  * Collect password response packet from frontend.
844  *
845  * Returns NULL if couldn't get password, else palloc'd string.
846  */
847 static char *
848 recv_password_packet(Port *port)
849 {
850         StringInfoData buf;
851
852         if (PG_PROTOCOL_MAJOR(port->proto) >= 3)
853         {
854                 /* Expect 'p' message type */
855                 int                     mtype;
856
857                 mtype = pq_getbyte();
858                 if (mtype != 'p')
859                 {
860                         /*
861                          * If the client just disconnects without offering a password,
862                          * don't make a log entry.  This is legal per protocol spec and in
863                          * fact commonly done by psql, so complaining just clutters the
864                          * log.
865                          */
866                         if (mtype != EOF)
867                                 ereport(COMMERROR,
868                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
869                                         errmsg("expected password response, got message type %d",
870                                                    mtype)));
871                         return NULL;            /* EOF or bad message type */
872                 }
873         }
874         else
875         {
876                 /* For pre-3.0 clients, avoid log entry if they just disconnect */
877                 if (pq_peekbyte() == EOF)
878                         return NULL;            /* EOF */
879         }
880
881         initStringInfo(&buf);
882         if (pq_getmessage(&buf, 1000))          /* receive password */
883         {
884                 /* EOF - pq_getmessage already logged a suitable message */
885                 pfree(buf.data);
886                 return NULL;
887         }
888
889         /*
890          * Apply sanity check: password packet length should agree with length of
891          * contained string.  Note it is safe to use strlen here because
892          * StringInfo is guaranteed to have an appended '\0'.
893          */
894         if (strlen(buf.data) + 1 != buf.len)
895                 ereport(COMMERROR,
896                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
897                                  errmsg("invalid password packet size")));
898
899         /* Do not echo password to logs, for security. */
900         ereport(DEBUG5,
901                         (errmsg("received password packet")));
902
903         /*
904          * Return the received string.  Note we do not attempt to do any
905          * character-set conversion on it; since we don't yet know the client's
906          * encoding, there wouldn't be much point.
907          */
908         return buf.data;
909 }
910
911
912 /*
913  * Called when we have sent an authorization request for a password.
914  * Get the response and check it.
915  */
916 static int
917 recv_and_check_password_packet(Port *port)
918 {
919         char       *passwd;
920         int                     result;
921
922         passwd = recv_password_packet(port);
923
924         if (passwd == NULL)
925                 return STATUS_EOF;              /* client wouldn't send password */
926
927         result = md5_crypt_verify(port, port->user_name, passwd);
928
929         pfree(passwd);
930
931         return result;
932 }