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