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