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