1 /*-------------------------------------------------------------------------
4 * Routines to handle network authentication
6 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/libpq/auth.c,v 1.88 2002/08/30 16:00:41 momjian Exp $
13 *-------------------------------------------------------------------------
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)
23 #include <sys/ucred.h>
26 #include <netinet/in.h>
27 #include <arpa/inet.h>
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"
39 static void sendAuthRequest(Port *port, AuthRequest areq);
40 static void auth_failed(Port *port, int status);
41 static int recv_and_check_password_packet(Port *port);
43 char *pg_krb_server_keyfile;
46 #include <security/pam_appl.h>
48 #define PGSQL_PAM_SERVICE "postgresql" /* Service name passed to PAM */
50 static int CheckPAMAuth(Port *port, char *user, char *password);
51 static int pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg,
52 struct pam_response ** resp, void *appdata_ptr);
54 static struct pam_conv pam_passw_conv = {
55 &pam_passwd_conv_proc,
59 static char *pam_passwd = NULL; /* Workaround for Solaris 2.6 brokenness */
60 static Port *pam_port_cludge; /* Workaround for passing "Port *port"
61 * into pam_passwd_conv_proc */
65 /*----------------------------------------------------------------
66 * MIT Kerberos authentication system - protocol version 4
67 *----------------------------------------------------------------
73 * pg_krb4_recvauth -- server routine to receive authentication information
76 * Nothing unusual here, except that we compare the username obtained from
77 * the client's setup packet to the authenticated name. (We have to retain
78 * the name in the setup packet since we have to retain the ability to handle
79 * unauthenticated connections.)
82 pg_krb4_recvauth(Port *port)
84 long krbopts = 0; /* one-way authentication */
86 char instance[INST_SZ + 1],
87 version[KRB_SENDAUTH_VLEN + 1];
89 Key_schedule key_sched;
92 strcpy(instance, "*"); /* don't care, but arg gets expanded
94 status = krb_recvauth(krbopts,
102 pg_krb_server_keyfile,
105 if (status != KSUCCESS)
107 elog(LOG, "pg_krb4_recvauth: kerberos error: %s",
108 krb_err_txt[status]);
111 if (strncmp(version, PG_KRB4_VERSION, KRB_SENDAUTH_VLEN) != 0)
113 elog(LOG, "pg_krb4_recvauth: protocol version \"%s\" != \"%s\"",
114 version, PG_KRB4_VERSION);
117 if (strncmp(port->user, auth_data.pname, SM_DATABASE_USER) != 0)
119 elog(LOG, "pg_krb4_recvauth: name \"%s\" != \"%s\"",
120 port->user, auth_data.pname);
129 pg_krb4_recvauth(Port *port)
131 elog(LOG, "pg_krb4_recvauth: Kerberos not implemented on this server");
139 /*----------------------------------------------------------------
140 * MIT Kerberos authentication system - protocol version 5
141 *----------------------------------------------------------------
148 * pg_an_to_ln -- return the local name corresponding to an authentication
151 * XXX Assumes that the first aname component is the user name. This is NOT
152 * necessarily so, since an aname can actually be something out of your
153 * worst X.400 nightmare, like
154 * ORGANIZATION=U. C. Berkeley/NAME=Paul M. Aoki@CS.BERKELEY.EDU
155 * Note that the MIT an_to_ln code does the same thing if you don't
156 * provide an aname mapping database...it may be a better idea to use
157 * krb5_an_to_ln, except that it punts if multiple components are found,
158 * and we can't afford to punt.
161 pg_an_to_ln(char *aname)
165 if ((p = strchr(aname, '/')) || (p = strchr(aname, '@')))
172 * Various krb5 state which is not connection specfic, and a flag to
173 * indicate whether we have initialised it yet.
175 static int pg_krb5_initialised;
176 static krb5_context pg_krb5_context;
177 static krb5_keytab pg_krb5_keytab;
178 static krb5_principal pg_krb5_server;
184 krb5_error_code retval;
186 if (pg_krb5_initialised)
189 retval = krb5_init_context(&pg_krb5_context);
192 elog(LOG, "pg_krb5_init: krb5_init_context returned Kerberos error %d",
194 com_err("postgres", retval, "while initializing krb5");
198 retval = krb5_kt_resolve(pg_krb5_context, pg_krb_server_keyfile, &pg_krb5_keytab);
201 elog(LOG, "pg_krb5_init: krb5_kt_resolve returned Kerberos error %d",
203 com_err("postgres", retval, "while resolving keytab file %s",
204 pg_krb_server_keyfile);
205 krb5_free_context(pg_krb5_context);
209 retval = krb5_sname_to_principal(pg_krb5_context, NULL, PG_KRB_SRVNAM,
210 KRB5_NT_SRV_HST, &pg_krb5_server);
213 elog(LOG, "pg_krb5_init: krb5_sname_to_principal returned Kerberos error %d",
215 com_err("postgres", retval,
216 "while getting server principal for service %s",
218 krb5_kt_close(pg_krb5_context, pg_krb5_keytab);
219 krb5_free_context(pg_krb5_context);
223 pg_krb5_initialised = 1;
229 * pg_krb5_recvauth -- server routine to receive authentication information
232 * We still need to compare the username obtained from the client's setup
233 * packet to the authenticated name, as described in pg_krb4_recvauth. This
234 * is a bit more problematic in v5, as described above in pg_an_to_ln.
236 * We have our own keytab file because postgres is unlikely to run as root,
237 * and so cannot read the default keytab.
240 pg_krb5_recvauth(Port *port)
242 krb5_error_code retval;
244 krb5_auth_context auth_context = NULL;
248 ret = pg_krb5_init();
249 if (ret != STATUS_OK)
252 retval = krb5_recvauth(pg_krb5_context, &auth_context,
253 (krb5_pointer) & port->sock, PG_KRB_SRVNAM,
254 pg_krb5_server, 0, pg_krb5_keytab, &ticket);
257 elog(LOG, "pg_krb5_recvauth: krb5_recvauth returned Kerberos error %d",
259 com_err("postgres", retval, "from krb5_recvauth");
264 * The "client" structure comes out of the ticket and is therefore
265 * authenticated. Use it to check the username obtained from the
266 * postmaster startup packet.
268 * I have no idea why this is considered necessary.
270 #if defined(HAVE_KRB5_TICKET_ENC_PART2)
271 retval = krb5_unparse_name(pg_krb5_context,
272 ticket->enc_part2->client, &kusername);
273 #elif defined(HAVE_KRB5_TICKET_CLIENT)
274 retval = krb5_unparse_name(pg_krb5_context,
275 ticket->client, &kusername);
277 #error "bogus configuration"
281 elog(LOG, "pg_krb5_recvauth: krb5_unparse_name returned Kerberos error %d",
283 com_err("postgres", retval, "while unparsing client name");
284 krb5_free_ticket(pg_krb5_context, ticket);
285 krb5_auth_con_free(pg_krb5_context, auth_context);
289 kusername = pg_an_to_ln(kusername);
290 if (strncmp(port->user, kusername, SM_DATABASE_USER))
292 elog(LOG, "pg_krb5_recvauth: user name \"%s\" != krb5 name \"%s\"",
293 port->user, kusername);
299 krb5_free_ticket(pg_krb5_context, ticket);
300 krb5_auth_con_free(pg_krb5_context, auth_context);
309 pg_krb5_recvauth(Port *port)
311 elog(LOG, "pg_krb5_recvauth: Kerberos not implemented on this server");
319 * Tell the user the authentication failed, but not (much about) why.
321 * There is a tradeoff here between security concerns and making life
322 * unnecessarily difficult for legitimate users. We would not, for example,
323 * want to report the password we were expecting to receive...
324 * But it seems useful to report the username and authorization method
325 * in use, and these are items that must be presumed known to an attacker
327 * Note that many sorts of failure report additional information in the
328 * postmaster log, which we hope is only readable by good guys.
331 auth_failed(Port *port, int status)
333 const char *authmethod = "Unknown auth method:";
336 * If we failed due to EOF from client, just quit; there's no point in
337 * trying to send a message to the client, and not much point in
338 * logging the failure in the postmaster log. (Logging the failure
339 * might be desirable, were it not for the fact that libpq closes the
340 * connection unceremoniously if challenged for a password when it
341 * hasn't got one to send. We'll get a useless log entry for every
342 * psql connection under password auth, even if it's perfectly
343 * successful, if we log STATUS_EOF events.)
345 if (status == STATUS_EOF)
348 switch (port->auth_method)
351 authmethod = "Rejected host:";
354 authmethod = "Kerberos4";
357 authmethod = "Kerberos5";
360 authmethod = "Trusted";
363 authmethod = "IDENT";
368 authmethod = "Password";
377 elog(FATAL, "%s authentication failed for user \"%s\"",
378 authmethod, port->user);
384 * Client authentication starts here. If there is an error, this
385 * function does not return and the backend process is terminated.
388 ClientAuthentication(Port *port)
390 int status = STATUS_ERROR;
393 * Get the authentication method to use for this frontend/database
394 * combination. Note: a failure return indicates a problem with the
395 * hba config file, not with the request. hba.c should have dropped
396 * an error message into the postmaster logfile if it failed.
398 if (hba_getauthmethod(port) != STATUS_OK)
399 elog(FATAL, "Missing or erroneous pg_hba.conf file, see postmaster log for details");
401 switch (port->auth_method)
406 * This could have come from an explicit "reject" entry in
407 * pg_hba.conf, but more likely it means there was no matching
408 * entry. Take pity on the poor user and issue a helpful
409 * error message. NOTE: this is not a security breach,
410 * because all the info reported here is known at the frontend
411 * and must be assumed known to bad guys. We're merely helping
412 * out the less clueful good guys.
415 const char *hostinfo = "localhost";
417 if (port->raddr.sa.sa_family == AF_INET)
418 hostinfo = inet_ntoa(port->raddr.in.sin_addr);
420 "No pg_hba.conf entry for host %s, user %s, database %s",
421 hostinfo, port->user, port->database);
426 sendAuthRequest(port, AUTH_REQ_KRB4);
427 status = pg_krb4_recvauth(port);
431 sendAuthRequest(port, AUTH_REQ_KRB5);
432 status = pg_krb5_recvauth(port);
436 #if !defined(SO_PEERCRED) && (defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || (defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS)))
439 * If we are doing ident on unix-domain sockets, use SCM_CREDS
440 * only if it is defined and SO_PEERCRED isn't.
442 #if defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED)
445 * Receive credentials on next message receipt, BSD/OS,
446 * NetBSD. We need to set this before the client sends the
452 if (setsockopt(port->sock, 0, LOCAL_CREDS, &on, sizeof(on)) < 0)
453 elog(FATAL, "pg_local_sendauth: can't do setsockopt: %m");
456 if (port->raddr.sa.sa_family == AF_UNIX)
457 sendAuthRequest(port, AUTH_REQ_SCM_CREDS);
459 status = authident(port);
463 sendAuthRequest(port, AUTH_REQ_MD5);
464 status = recv_and_check_password_packet(port);
468 sendAuthRequest(port, AUTH_REQ_CRYPT);
469 status = recv_and_check_password_packet(port);
473 sendAuthRequest(port, AUTH_REQ_PASSWORD);
474 status = recv_and_check_password_packet(port);
479 pam_port_cludge = port;
480 status = CheckPAMAuth(port, port->user, "");
489 if (status == STATUS_OK)
490 sendAuthRequest(port, AUTH_REQ_OK);
492 auth_failed(port, status);
497 * Send an authentication request packet to the frontend.
500 sendAuthRequest(Port *port, AuthRequest areq)
504 pq_beginmessage(&buf);
505 pq_sendbyte(&buf, 'R');
506 pq_sendint(&buf, (int32) areq, sizeof(int32));
508 /* Add the salt for encrypted passwords. */
509 if (areq == AUTH_REQ_MD5)
510 pq_sendbytes(&buf, port->md5Salt, 4);
511 else if (areq == AUTH_REQ_CRYPT)
512 pq_sendbytes(&buf, port->cryptSalt, 2);
517 * Flush message so client will see it, except for AUTH_REQ_OK,
518 * which need not be sent until we are ready for queries.
520 if (areq != AUTH_REQ_OK)
528 * PAM conversation function
532 pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg, struct pam_response ** resp, void *appdata_ptr)
537 if (num_msg != 1 || msg[0]->msg_style != PAM_PROMPT_ECHO_OFF)
539 switch (msg[0]->msg_style)
542 elog(LOG, "pam_passwd_conv_proc: Error from underlying PAM layer: '%s'",
546 elog(LOG, "pam_passwd_conv_proc: Unexpected PAM conversation %d/'%s'",
547 msg[0]->msg_style, msg[0]->msg);
555 * Workaround for Solaris 2.6 where the PAM library is broken and
556 * does not pass appdata_ptr to the conversation routine
558 appdata_ptr = pam_passwd;
562 * Password wasn't passed to PAM the first time around - let's go ask
563 * the client to send a password, which we then stuff into PAM.
565 if (strlen(appdata_ptr) == 0)
567 sendAuthRequest(pam_port_cludge, AUTH_REQ_PASSWORD);
568 if (pq_eof() == EOF || pq_getint(&len, 4) == EOF)
570 return PAM_CONV_ERR; /* client didn't want to send password */
573 initStringInfo(&buf);
576 /* Do not echo failed password to logs, for security. */
577 elog(DEBUG5, "received PAM packet");
579 if (strlen(buf.data) == 0)
581 elog(LOG, "pam_passwd_conv_proc: no password");
584 appdata_ptr = buf.data;
588 * Explicitly not using palloc here - PAM will free this memory in
591 *resp = calloc(num_msg, sizeof(struct pam_response));
594 elog(LOG, "pam_passwd_conv_proc: Out of memory!");
600 (*resp)[0].resp = strdup((char *) appdata_ptr);
601 (*resp)[0].resp_retcode = 0;
603 return ((*resp)[0].resp ? PAM_SUCCESS : PAM_CONV_ERR);
608 * Check authentication against PAM.
611 CheckPAMAuth(Port *port, char *user, char *password)
614 pam_handle_t *pamh = NULL;
617 * Apparently, Solaris 2.6 is broken, and needs ugly static variable
620 pam_passwd = password;
623 * Set the application data portion of the conversation struct This is
624 * later used inside the PAM conversation to pass the password to the
625 * authentication module.
627 pam_passw_conv.appdata_ptr = (char *) password; /* from password above,
630 /* Optionally, one can set the service name in pg_hba.conf */
631 if (port->auth_arg[0] == '\0')
632 retval = pam_start(PGSQL_PAM_SERVICE, "pgsql@", &pam_passw_conv, &pamh);
634 retval = pam_start(port->auth_arg, "pgsql@", &pam_passw_conv, &pamh);
636 if (retval != PAM_SUCCESS)
638 elog(LOG, "CheckPAMAuth: Failed to create PAM authenticator: '%s'",
639 pam_strerror(pamh, retval));
640 pam_passwd = NULL; /* Unset pam_passwd */
644 retval = pam_set_item(pamh, PAM_USER, user);
646 if (retval != PAM_SUCCESS)
648 elog(LOG, "CheckPAMAuth: pam_set_item(PAM_USER) failed: '%s'",
649 pam_strerror(pamh, retval));
650 pam_passwd = NULL; /* Unset pam_passwd */
654 retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv);
656 if (retval != PAM_SUCCESS)
658 elog(LOG, "CheckPAMAuth: pam_set_item(PAM_CONV) failed: '%s'",
659 pam_strerror(pamh, retval));
660 pam_passwd = NULL; /* Unset pam_passwd */
664 retval = pam_authenticate(pamh, 0);
666 if (retval != PAM_SUCCESS)
668 elog(LOG, "CheckPAMAuth: pam_authenticate failed: '%s'",
669 pam_strerror(pamh, retval));
670 pam_passwd = NULL; /* Unset pam_passwd */
674 retval = pam_acct_mgmt(pamh, 0);
676 if (retval != PAM_SUCCESS)
678 elog(LOG, "CheckPAMAuth: pam_acct_mgmt failed: '%s'",
679 pam_strerror(pamh, retval));
680 pam_passwd = NULL; /* Unset pam_passwd */
684 retval = pam_end(pamh, retval);
686 if (retval != PAM_SUCCESS)
688 elog(LOG, "CheckPAMAuth: Failed to release PAM authenticator: '%s'",
689 pam_strerror(pamh, retval));
692 pam_passwd = NULL; /* Unset pam_passwd */
694 return (retval == PAM_SUCCESS ? STATUS_OK : STATUS_ERROR);
700 * Called when we have received the password packet.
703 recv_and_check_password_packet(Port *port)
709 if (pq_eof() == EOF || pq_getint(&len, 4) == EOF)
710 return STATUS_EOF; /* client didn't want to send password */
712 initStringInfo(&buf);
713 if (pq_getstr(&buf) == EOF) /* receive password */
719 * We don't actually use the password packet length the frontend
720 * sent us; however, it's a reasonable sanity check to ensure that
721 * we actually read as much data as we expected to.
723 * The password packet size is the length of the buffer, plus the
724 * size field itself (4 bytes), plus a 1-byte terminator.
726 if (len != (buf.len + 4 + 1))
727 elog(LOG, "unexpected password packet size: read %d, expected %d",
728 buf.len + 4 + 1, len);
730 /* Do not echo password to logs, for security. */
731 elog(DEBUG5, "received password packet");
733 result = md5_crypt_verify(port, port->user, buf.data);