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