OSDN Git Service

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