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