1 /*-------------------------------------------------------------------------
4 * Routines to handle network authentication
6 * Portions Copyright (c) 1996-2001, 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.79 2002/03/05 07:57:45 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>
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"
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);
44 char *pg_krb_server_keyfile;
47 #include <security/pam_appl.h>
49 #define PGSQL_PAM_SERVICE "postgresql" /* Service name passed to PAM */
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);
55 static struct pam_conv pam_passw_conv = {
56 &pam_passwd_conv_proc,
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 */
66 /*----------------------------------------------------------------
67 * MIT Kerberos authentication system - protocol version 4
68 *----------------------------------------------------------------
74 * pg_krb4_recvauth -- server routine to receive authentication information
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.)
83 pg_krb4_recvauth(Port *port)
85 long krbopts = 0; /* one-way authentication */
87 char instance[INST_SZ + 1],
88 version[KRB_SENDAUTH_VLEN + 1];
90 Key_schedule key_sched;
93 strcpy(instance, "*"); /* don't care, but arg gets expanded
95 status = krb_recvauth(krbopts,
103 pg_krb_server_keyfile,
106 if (status != KSUCCESS)
108 elog(LOG, "pg_krb4_recvauth: kerberos error: %s",
109 krb_err_txt[status]);
112 if (strncmp(version, PG_KRB4_VERSION, KRB_SENDAUTH_VLEN) != 0)
114 elog(LOG, "pg_krb4_recvauth: protocol version \"%s\" != \"%s\"",
115 version, PG_KRB4_VERSION);
118 if (strncmp(port->user, auth_data.pname, SM_USER) != 0)
120 elog(LOG, "pg_krb4_recvauth: name \"%s\" != \"%s\"",
121 port->user, auth_data.pname);
130 pg_krb4_recvauth(Port *port)
132 elog(LOG, "pg_krb4_recvauth: Kerberos not implemented on this server");
140 /*----------------------------------------------------------------
141 * MIT Kerberos authentication system - protocol version 5
142 *----------------------------------------------------------------
149 * pg_an_to_ln -- return the local name corresponding to an authentication
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.
162 pg_an_to_ln(char *aname)
166 if ((p = strchr(aname, '/')) || (p = strchr(aname, '@')))
173 * Various krb5 state which is not connection specfic, and a flag to
174 * indicate whether we have initialised it yet.
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;
185 krb5_error_code retval;
187 if (pg_krb5_initialised)
190 retval = krb5_init_context(&pg_krb5_context);
193 elog(LOG, "pg_krb5_init: krb5_init_context returned Kerberos error %d",
195 com_err("postgres", retval, "while initializing krb5");
199 retval = krb5_kt_resolve(pg_krb5_context, pg_krb_server_keyfile, &pg_krb5_keytab);
202 elog(LOG, "pg_krb5_init: krb5_kt_resolve returned Kerberos error %d",
204 com_err("postgres", retval, "while resolving keytab file %s",
205 pg_krb_server_keyfile);
206 krb5_free_context(pg_krb5_context);
210 retval = krb5_sname_to_principal(pg_krb5_context, NULL, PG_KRB_SRVNAM,
211 KRB5_NT_SRV_HST, &pg_krb5_server);
214 elog(LOG, "pg_krb5_init: krb5_sname_to_principal returned Kerberos error %d",
216 com_err("postgres", retval,
217 "while getting server principal for service %s",
219 krb5_kt_close(pg_krb5_context, pg_krb5_keytab);
220 krb5_free_context(pg_krb5_context);
224 pg_krb5_initialised = 1;
230 * pg_krb5_recvauth -- server routine to receive authentication information
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.
237 * We have our own keytab file because postgres is unlikely to run as root,
238 * and so cannot read the default keytab.
241 pg_krb5_recvauth(Port *port)
243 krb5_error_code retval;
245 krb5_auth_context auth_context = NULL;
249 ret = pg_krb5_init();
250 if (ret != STATUS_OK)
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);
258 elog(LOG, "pg_krb5_recvauth: krb5_recvauth returned Kerberos error %d",
260 com_err("postgres", retval, "from krb5_recvauth");
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.
269 * I have no idea why this is considered necessary.
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);
278 #error "bogus configuration"
282 elog(LOG, "pg_krb5_recvauth: krb5_unparse_name returned Kerberos error %d",
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);
290 kusername = pg_an_to_ln(kusername);
291 if (strncmp(port->user, kusername, SM_USER))
293 elog(LOG, "pg_krb5_recvauth: user name \"%s\" != krb5 name \"%s\"",
294 port->user, kusername);
300 krb5_free_ticket(pg_krb5_context, ticket);
301 krb5_auth_con_free(pg_krb5_context, auth_context);
310 pg_krb5_recvauth(Port *port)
312 elog(LOG, "pg_krb5_recvauth: Kerberos not implemented on this server");
320 * Handle a v0 password packet.
323 recv_and_check_passwordv0(Port *port)
327 PasswordPacketV0 *pp;
334 if (pq_getint(&len, 4) == EOF)
338 if (pq_getbytes(buf, len) == EOF)
344 pp = (PasswordPacketV0 *) buf;
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.
350 user = password = NULL;
352 len -= sizeof(pp->unused);
354 cp = start = pp->data;
370 if (user == NULL || password == NULL)
372 elog(LOG, "pg_password_recvauth: badly formed password packet");
373 status = STATUS_ERROR;
379 /* Check the password. */
381 saved = port->auth_method;
382 port->auth_method = uaPassword;
384 status = checkPassword(port, user, password);
386 port->auth_method = saved;
388 /* Adjust the result if necessary. */
389 if (map_old_to_new(port, uaPassword, status) != STATUS_OK)
390 status = STATUS_ERROR;
400 * Tell the user the authentication failed, but not (much about) why.
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
408 * Note that many sorts of failure report additional information in the
409 * postmaster log, which we hope is only readable by good guys.
412 auth_failed(Port *port, int status)
414 const char *authmethod = "Unknown auth method:";
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.)
426 if (status == STATUS_EOF)
429 switch (port->auth_method)
432 authmethod = "Rejected host:";
435 authmethod = "Kerberos4";
438 authmethod = "Kerberos5";
441 authmethod = "Trusted";
444 authmethod = "IDENT";
449 authmethod = "Password";
458 elog(FATAL, "%s authentication failed for user \"%s\"",
459 authmethod, port->user);
465 * Client authentication starts here. If there is an error, this
466 * function does not return and the backend process is terminated.
469 ClientAuthentication(Port *port)
471 int status = STATUS_ERROR;
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.
479 if (hba_getauthmethod(port) != STATUS_OK)
480 elog(FATAL, "Missing or erroneous pg_hba.conf file, see postmaster log for details");
482 /* Handle old style authentication. */
483 if (PG_PROTOCOL_MAJOR(port->proto) == 0)
485 status = old_be_recvauth(port);
486 if (status != STATUS_OK)
487 auth_failed(port, status);
491 /* Handle new style authentication. */
492 switch (port->auth_method)
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.
506 const char *hostinfo = "localhost";
508 if (port->raddr.sa.sa_family == AF_INET)
509 hostinfo = inet_ntoa(port->raddr.in.sin_addr);
511 "No pg_hba.conf entry for host %s, user %s, database %s",
512 hostinfo, port->user, port->database);
517 sendAuthRequest(port, AUTH_REQ_KRB4);
518 status = pg_krb4_recvauth(port);
522 sendAuthRequest(port, AUTH_REQ_KRB5);
523 status = pg_krb5_recvauth(port);
527 #if !defined(SO_PEERCRED) && (defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || (defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS)))
530 * If we are doing ident on unix-domain sockets, use SCM_CREDS
531 * only if it is defined and SO_PEERCRED isn't.
533 #if defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED)
536 * Receive credentials on next message receipt, BSD/OS,
537 * NetBSD. We need to set this before the client sends the
543 if (setsockopt(port->sock, 0, LOCAL_CREDS, &on, sizeof(on)) < 0)
544 elog(FATAL, "pg_local_sendauth: can't do setsockopt: %m");
547 if (port->raddr.sa.sa_family == AF_UNIX)
548 sendAuthRequest(port, AUTH_REQ_SCM_CREDS);
550 status = authident(port);
554 sendAuthRequest(port, AUTH_REQ_MD5);
555 status = recv_and_check_password_packet(port);
559 sendAuthRequest(port, AUTH_REQ_CRYPT);
560 status = recv_and_check_password_packet(port);
564 sendAuthRequest(port, AUTH_REQ_PASSWORD);
565 status = recv_and_check_password_packet(port);
570 pam_port_cludge = port;
571 status = CheckPAMAuth(port, port->user, "");
580 if (status == STATUS_OK)
581 sendAuthRequest(port, AUTH_REQ_OK);
583 auth_failed(port, status);
588 * Send an authentication request packet to the frontend.
591 sendAuthRequest(Port *port, AuthRequest areq)
595 pq_beginmessage(&buf);
596 pq_sendbyte(&buf, 'R');
597 pq_sendint(&buf, (int32) areq, sizeof(int32));
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);
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.
611 if (areq != AUTH_REQ_OK)
619 * PAM conversation function
623 pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg, struct pam_response ** resp, void *appdata_ptr)
628 if (num_msg != 1 || msg[0]->msg_style != PAM_PROMPT_ECHO_OFF)
630 switch (msg[0]->msg_style)
633 elog(LOG, "pam_passwd_conv_proc: Error from underlying PAM layer: '%s'",
637 elog(LOG, "pam_passwd_conv_proc: Unexpected PAM conversation %d/'%s'",
638 msg[0]->msg_style, msg[0]->msg);
646 * Workaround for Solaris 2.6 where the PAM library is broken and
647 * does not pass appdata_ptr to the conversation routine
649 appdata_ptr = pam_passwd;
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.
656 if (strlen(appdata_ptr) == 0)
658 sendAuthRequest(pam_port_cludge, AUTH_REQ_PASSWORD);
659 if (pq_eof() == EOF || pq_getint(&len, 4) == EOF)
661 return PAM_CONV_ERR; /* client didn't want to send password */
664 initStringInfo(&buf);
667 /* Do not echo failed password to logs, for security. */
668 elog(DEBUG5, "received PAM packet");
670 if (strlen(buf.data) == 0)
672 elog(LOG, "pam_passwd_conv_proc: no password");
675 appdata_ptr = buf.data;
679 * Explicitly not using palloc here - PAM will free this memory in
682 *resp = calloc(num_msg, sizeof(struct pam_response));
685 elog(LOG, "pam_passwd_conv_proc: Out of memory!");
691 (*resp)[0].resp = strdup((char *) appdata_ptr);
692 (*resp)[0].resp_retcode = 0;
694 return ((*resp)[0].resp ? PAM_SUCCESS : PAM_CONV_ERR);
699 * Check authentication against PAM.
702 CheckPAMAuth(Port *port, char *user, char *password)
705 pam_handle_t *pamh = NULL;
708 * Apparently, Solaris 2.6 is broken, and needs ugly static variable
711 pam_passwd = password;
714 * Set the application data portion of the conversation struct This is
715 * later used inside the PAM conversation to pass the password to the
716 * authentication module.
718 pam_passw_conv.appdata_ptr = (char *) password; /* from password above,
721 /* Optionally, one can set the service name in pg_hba.conf */
722 if (port->auth_arg[0] == '\0')
723 retval = pam_start(PGSQL_PAM_SERVICE, "pgsql@", &pam_passw_conv, &pamh);
725 retval = pam_start(port->auth_arg, "pgsql@", &pam_passw_conv, &pamh);
727 if (retval != PAM_SUCCESS)
729 elog(LOG, "CheckPAMAuth: Failed to create PAM authenticator: '%s'",
730 pam_strerror(pamh, retval));
731 pam_passwd = NULL; /* Unset pam_passwd */
735 retval = pam_set_item(pamh, PAM_USER, user);
737 if (retval != PAM_SUCCESS)
739 elog(LOG, "CheckPAMAuth: pam_set_item(PAM_USER) failed: '%s'",
740 pam_strerror(pamh, retval));
741 pam_passwd = NULL; /* Unset pam_passwd */
745 retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv);
747 if (retval != PAM_SUCCESS)
749 elog(LOG, "CheckPAMAuth: pam_set_item(PAM_CONV) failed: '%s'",
750 pam_strerror(pamh, retval));
751 pam_passwd = NULL; /* Unset pam_passwd */
755 retval = pam_authenticate(pamh, 0);
757 if (retval != PAM_SUCCESS)
759 elog(LOG, "CheckPAMAuth: pam_authenticate failed: '%s'",
760 pam_strerror(pamh, retval));
761 pam_passwd = NULL; /* Unset pam_passwd */
765 retval = pam_acct_mgmt(pamh, 0);
767 if (retval != PAM_SUCCESS)
769 elog(LOG, "CheckPAMAuth: pam_acct_mgmt failed: '%s'",
770 pam_strerror(pamh, retval));
771 pam_passwd = NULL; /* Unset pam_passwd */
775 retval = pam_end(pamh, retval);
777 if (retval != PAM_SUCCESS)
779 elog(LOG, "CheckPAMAuth: Failed to release PAM authenticator: '%s'",
780 pam_strerror(pamh, retval));
783 pam_passwd = NULL; /* Unset pam_passwd */
785 return (retval == PAM_SUCCESS ? STATUS_OK : STATUS_ERROR);
791 * Called when we have received the password packet.
794 recv_and_check_password_packet(Port *port)
800 if (pq_eof() == EOF || pq_getint(&len, 4) == EOF)
801 return STATUS_EOF; /* client didn't want to send password */
803 initStringInfo(&buf);
804 if (pq_getstr(&buf) == EOF) /* receive password */
810 /* Do not echo failed password to logs, for security. */
811 elog(DEBUG5, "received password packet");
813 result = checkPassword(port, port->user, buf.data);
820 * Handle `password' and `crypt' records. If an auth argument was
821 * specified, use the respective file. Else use pg_shadow passwords.
824 checkPassword(Port *port, char *user, char *password)
826 if (port->auth_arg[0] != '\0')
827 return verify_password(port, user, password);
829 return md5_crypt_verify(port, user, password);
834 * Server demux routine for incoming authentication information for protocol
838 old_be_recvauth(Port *port)
841 MsgType msgtype = (MsgType) port->proto;
843 /* Handle the authentication that's offered. */
846 case STARTUP_KRB4_MSG:
847 status = map_old_to_new(port, uaKrb4, pg_krb4_recvauth(port));
850 case STARTUP_KRB5_MSG:
851 status = map_old_to_new(port, uaKrb5, pg_krb5_recvauth(port));
855 status = map_old_to_new(port, uaTrust, STATUS_OK);
858 case STARTUP_PASSWORD_MSG:
859 status = recv_and_check_passwordv0(port);
863 elog(LOG, "Invalid startup message type: %u", msgtype);
873 * The old style authentication has been done. Modify the result of this (eg.
874 * allow the connection anyway, disallow it anyway, or use the result)
875 * depending on what authentication we really want to use.
878 map_old_to_new(Port *port, UserAuth old, int status)
880 switch (port->auth_method)
888 status = STATUS_ERROR;
893 status = STATUS_ERROR;
898 status = STATUS_ERROR;
906 status = authident(port);
910 if (old != uaPassword)
911 status = STATUS_ERROR;