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.103 2003/06/25 01:19:47 momjian Exp $
13 *-------------------------------------------------------------------------
18 #include <sys/param.h>
19 #include <sys/socket.h>
20 #if defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED)
22 #include <sys/ucred.h>
25 #include <netinet/in.h>
26 #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/pqcomm.h"
33 #include "libpq/pqformat.h"
34 #include "miscadmin.h"
35 #include "storage/ipc.h"
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);
43 char *pg_krb_server_keyfile;
46 #ifdef HAVE_PAM_PAM_APPL_H
47 #include <pam/pam_appl.h>
49 #ifdef HAVE_SECURITY_PAM_APPL_H
50 #include <security/pam_appl.h>
53 #define PGSQL_PAM_SERVICE "postgresql" /* Service name passed to PAM */
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);
59 static struct pam_conv pam_passw_conv = {
60 &pam_passwd_conv_proc,
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 */
70 /*----------------------------------------------------------------
71 * MIT Kerberos authentication system - protocol version 4
72 *----------------------------------------------------------------
78 * pg_krb4_recvauth -- server routine to receive authentication information
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.)
87 pg_krb4_recvauth(Port *port)
89 long krbopts = 0; /* one-way authentication */
91 char instance[INST_SZ + 1],
92 version[KRB_SENDAUTH_VLEN + 1];
94 Key_schedule key_sched;
97 strcpy(instance, "*"); /* don't care, but arg gets expanded
99 status = krb_recvauth(krbopts,
107 pg_krb_server_keyfile,
110 if (status != KSUCCESS)
112 elog(LOG, "pg_krb4_recvauth: kerberos error: %s",
113 krb_err_txt[status]);
116 if (strncmp(version, PG_KRB4_VERSION, KRB_SENDAUTH_VLEN) != 0)
118 elog(LOG, "pg_krb4_recvauth: protocol version \"%s\" != \"%s\"",
119 version, PG_KRB4_VERSION);
122 if (strncmp(port->user_name, auth_data.pname, SM_DATABASE_USER) != 0)
124 elog(LOG, "pg_krb4_recvauth: name \"%s\" != \"%s\"",
125 port->user_name, auth_data.pname);
134 pg_krb4_recvauth(Port *port)
136 elog(LOG, "pg_krb4_recvauth: Kerberos not implemented on this server");
143 /*----------------------------------------------------------------
144 * MIT Kerberos authentication system - protocol version 5
145 *----------------------------------------------------------------
152 * pg_an_to_ln -- return the local name corresponding to an authentication
155 * XXX Assumes that the first aname component is the user name. This is NOT
156 * necessarily so, since an aname can actually be something out of your
157 * worst X.400 nightmare, like
158 * ORGANIZATION=U. C. Berkeley/NAME=Paul M. Aoki@CS.BERKELEY.EDU
159 * Note that the MIT an_to_ln code does the same thing if you don't
160 * provide an aname mapping database...it may be a better idea to use
161 * krb5_an_to_ln, except that it punts if multiple components are found,
162 * and we can't afford to punt.
165 pg_an_to_ln(char *aname)
169 if ((p = strchr(aname, '/')) || (p = strchr(aname, '@')))
176 * Various krb5 state which is not connection specfic, and a flag to
177 * indicate whether we have initialised it yet.
179 static int pg_krb5_initialised;
180 static krb5_context pg_krb5_context;
181 static krb5_keytab pg_krb5_keytab;
182 static krb5_principal pg_krb5_server;
188 krb5_error_code retval;
190 if (pg_krb5_initialised)
193 retval = krb5_init_context(&pg_krb5_context);
196 elog(LOG, "pg_krb5_init: krb5_init_context returned Kerberos error %d",
198 com_err("postgres", retval, "while initializing krb5");
202 retval = krb5_kt_resolve(pg_krb5_context, pg_krb_server_keyfile, &pg_krb5_keytab);
205 elog(LOG, "pg_krb5_init: krb5_kt_resolve returned Kerberos error %d",
207 com_err("postgres", retval, "while resolving keytab file %s",
208 pg_krb_server_keyfile);
209 krb5_free_context(pg_krb5_context);
213 retval = krb5_sname_to_principal(pg_krb5_context, NULL, PG_KRB_SRVNAM,
214 KRB5_NT_SRV_HST, &pg_krb5_server);
217 elog(LOG, "pg_krb5_init: krb5_sname_to_principal returned Kerberos error %d",
219 com_err("postgres", retval,
220 "while getting server principal for service %s",
222 krb5_kt_close(pg_krb5_context, pg_krb5_keytab);
223 krb5_free_context(pg_krb5_context);
227 pg_krb5_initialised = 1;
233 * pg_krb5_recvauth -- server routine to receive authentication information
236 * We still need to compare the username obtained from the client's setup
237 * packet to the authenticated name, as described in pg_krb4_recvauth. This
238 * is a bit more problematic in v5, as described above in pg_an_to_ln.
240 * We have our own keytab file because postgres is unlikely to run as root,
241 * and so cannot read the default keytab.
244 pg_krb5_recvauth(Port *port)
246 krb5_error_code retval;
248 krb5_auth_context auth_context = NULL;
252 ret = pg_krb5_init();
253 if (ret != STATUS_OK)
256 retval = krb5_recvauth(pg_krb5_context, &auth_context,
257 (krb5_pointer) & port->sock, PG_KRB_SRVNAM,
258 pg_krb5_server, 0, pg_krb5_keytab, &ticket);
261 elog(LOG, "pg_krb5_recvauth: krb5_recvauth returned Kerberos error %d",
263 com_err("postgres", retval, "from krb5_recvauth");
268 * The "client" structure comes out of the ticket and is therefore
269 * authenticated. Use it to check the username obtained from the
270 * postmaster startup packet.
272 * I have no idea why this is considered necessary.
274 #if defined(HAVE_KRB5_TICKET_ENC_PART2)
275 retval = krb5_unparse_name(pg_krb5_context,
276 ticket->enc_part2->client, &kusername);
277 #elif defined(HAVE_KRB5_TICKET_CLIENT)
278 retval = krb5_unparse_name(pg_krb5_context,
279 ticket->client, &kusername);
281 #error "bogus configuration"
285 elog(LOG, "pg_krb5_recvauth: krb5_unparse_name returned Kerberos error %d",
287 com_err("postgres", retval, "while unparsing client name");
288 krb5_free_ticket(pg_krb5_context, ticket);
289 krb5_auth_con_free(pg_krb5_context, auth_context);
293 kusername = pg_an_to_ln(kusername);
294 if (strncmp(port->user_name, kusername, SM_DATABASE_USER))
296 elog(LOG, "pg_krb5_recvauth: user name \"%s\" != krb5 name \"%s\"",
297 port->user_name, kusername);
303 krb5_free_ticket(pg_krb5_context, ticket);
304 krb5_auth_con_free(pg_krb5_context, auth_context);
313 pg_krb5_recvauth(Port *port)
315 elog(LOG, "pg_krb5_recvauth: Kerberos not implemented on this server");
322 * Tell the user the authentication failed, but not (much about) why.
324 * There is a tradeoff here between security concerns and making life
325 * unnecessarily difficult for legitimate users. We would not, for example,
326 * want to report the password we were expecting to receive...
327 * But it seems useful to report the username and authorization method
328 * in use, and these are items that must be presumed known to an attacker
330 * Note that many sorts of failure report additional information in the
331 * postmaster log, which we hope is only readable by good guys.
334 auth_failed(Port *port, int status)
336 const char *authmethod = "Unknown auth method:";
339 * If we failed due to EOF from client, just quit; there's no point in
340 * trying to send a message to the client, and not much point in
341 * logging the failure in the postmaster log. (Logging the failure
342 * might be desirable, were it not for the fact that libpq closes the
343 * connection unceremoniously if challenged for a password when it
344 * hasn't got one to send. We'll get a useless log entry for every
345 * psql connection under password auth, even if it's perfectly
346 * successful, if we log STATUS_EOF events.)
348 if (status == STATUS_EOF)
351 switch (port->auth_method)
354 authmethod = "Rejected host:";
357 authmethod = "Kerberos4";
360 authmethod = "Kerberos5";
363 authmethod = "Trusted";
366 authmethod = "IDENT";
371 authmethod = "Password";
380 elog(FATAL, "%s authentication failed for user \"%s\"",
381 authmethod, port->user_name);
387 * Client authentication starts here. If there is an error, this
388 * function does not return and the backend process is terminated.
391 ClientAuthentication(Port *port)
393 int status = STATUS_ERROR;
396 * Get the authentication method to use for this frontend/database
397 * combination. Note: a failure return indicates a problem with the
398 * hba config file, not with the request. hba.c should have dropped
399 * an error message into the postmaster logfile if it failed.
401 if (hba_getauthmethod(port) != STATUS_OK)
402 elog(FATAL, "Missing or erroneous pg_hba.conf file, see postmaster log for details");
404 switch (port->auth_method)
409 * This could have come from an explicit "reject" entry in
410 * pg_hba.conf, but more likely it means there was no matching
411 * entry. Take pity on the poor user and issue a helpful
412 * error message. NOTE: this is not a security breach,
413 * because all the info reported here is known at the frontend
414 * and must be assumed known to bad guys. We're merely helping
415 * out the less clueful good guys.
418 char hostinfo[NI_MAXHOST];
421 (struct sockaddr *)&port->raddr.addr,
423 hostinfo, sizeof(hostinfo),
424 NULL, 0, NI_NUMERICHOST);
427 "No pg_hba.conf entry for host %s, user %s, database %s",
428 hostinfo, port->user_name, port->database_name);
433 /* Kerberos 4 only seems to work with AF_INET. */
434 if (port->raddr.addr.ss_family != AF_INET
435 || port->laddr.addr.ss_family != AF_INET)
438 "Unsupported protocol for Kerberos 4");
440 sendAuthRequest(port, AUTH_REQ_KRB4);
441 status = pg_krb4_recvauth(port);
445 sendAuthRequest(port, AUTH_REQ_KRB5);
446 status = pg_krb5_recvauth(port);
450 #if defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || \
451 (defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS)) && \
452 !defined(HAVE_GETPEEREID) && !defined(SO_PEERCRED)
455 * If we are doing ident on unix-domain sockets, use SCM_CREDS
456 * only if it is defined and SO_PEERCRED isn't.
458 #if defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED)
461 * Receive credentials on next message receipt, BSD/OS,
462 * NetBSD. We need to set this before the client sends the
468 if (setsockopt(port->sock, 0, LOCAL_CREDS, &on, sizeof(on)) < 0)
469 elog(FATAL, "pg_local_sendauth: can't do setsockopt: %m");
472 if (port->raddr.addr.ss_family == AF_UNIX)
473 sendAuthRequest(port, AUTH_REQ_SCM_CREDS);
475 status = authident(port);
479 sendAuthRequest(port, AUTH_REQ_MD5);
480 status = recv_and_check_password_packet(port);
484 sendAuthRequest(port, AUTH_REQ_CRYPT);
485 status = recv_and_check_password_packet(port);
489 sendAuthRequest(port, AUTH_REQ_PASSWORD);
490 status = recv_and_check_password_packet(port);
495 pam_port_cludge = port;
496 status = CheckPAMAuth(port, port->user_name, "");
505 if (status == STATUS_OK)
506 sendAuthRequest(port, AUTH_REQ_OK);
508 auth_failed(port, status);
513 * Send an authentication request packet to the frontend.
516 sendAuthRequest(Port *port, AuthRequest areq)
520 pq_beginmessage(&buf, 'R');
521 pq_sendint(&buf, (int32) areq, sizeof(int32));
523 /* Add the salt for encrypted passwords. */
524 if (areq == AUTH_REQ_MD5)
525 pq_sendbytes(&buf, port->md5Salt, 4);
526 else if (areq == AUTH_REQ_CRYPT)
527 pq_sendbytes(&buf, port->cryptSalt, 2);
532 * Flush message so client will see it, except for AUTH_REQ_OK, which
533 * need not be sent until we are ready for queries.
535 if (areq != AUTH_REQ_OK)
543 * PAM conversation function
547 pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg,
548 struct pam_response ** resp, void *appdata_ptr)
550 if (num_msg != 1 || msg[0]->msg_style != PAM_PROMPT_ECHO_OFF)
552 switch (msg[0]->msg_style)
555 elog(LOG, "pam_passwd_conv_proc: Error from underlying PAM layer: '%s'",
559 elog(LOG, "pam_passwd_conv_proc: Unexpected PAM conversation %d/'%s'",
560 msg[0]->msg_style, msg[0]->msg);
568 * Workaround for Solaris 2.6 where the PAM library is broken and
569 * does not pass appdata_ptr to the conversation routine
571 appdata_ptr = pam_passwd;
575 * Password wasn't passed to PAM the first time around - let's go ask
576 * the client to send a password, which we then stuff into PAM.
578 if (strlen(appdata_ptr) == 0)
582 sendAuthRequest(pam_port_cludge, AUTH_REQ_PASSWORD);
583 passwd = recv_password_packet(pam_port_cludge);
586 return PAM_CONV_ERR; /* client didn't want to send password */
588 if (strlen(passwd) == 0)
590 elog(LOG, "pam_passwd_conv_proc: no password");
593 appdata_ptr = passwd;
597 * Explicitly not using palloc here - PAM will free this memory in
600 *resp = calloc(num_msg, sizeof(struct pam_response));
603 elog(LOG, "pam_passwd_conv_proc: Out of memory!");
607 (*resp)[0].resp = strdup((char *) appdata_ptr);
608 (*resp)[0].resp_retcode = 0;
610 return ((*resp)[0].resp ? PAM_SUCCESS : PAM_CONV_ERR);
615 * Check authentication against PAM.
618 CheckPAMAuth(Port *port, char *user, char *password)
621 pam_handle_t *pamh = NULL;
624 * Apparently, Solaris 2.6 is broken, and needs ugly static variable
627 pam_passwd = password;
630 * Set the application data portion of the conversation struct This is
631 * later used inside the PAM conversation to pass the password to the
632 * authentication module.
634 pam_passw_conv.appdata_ptr = (char *) password; /* from password above,
637 /* Optionally, one can set the service name in pg_hba.conf */
638 if (port->auth_arg && port->auth_arg[0] != '\0')
639 retval = pam_start(port->auth_arg, "pgsql@",
640 &pam_passw_conv, &pamh);
642 retval = pam_start(PGSQL_PAM_SERVICE, "pgsql@",
643 &pam_passw_conv, &pamh);
645 if (retval != PAM_SUCCESS)
647 elog(LOG, "CheckPAMAuth: Failed to create PAM authenticator: '%s'",
648 pam_strerror(pamh, retval));
649 pam_passwd = NULL; /* Unset pam_passwd */
653 retval = pam_set_item(pamh, PAM_USER, user);
655 if (retval != PAM_SUCCESS)
657 elog(LOG, "CheckPAMAuth: pam_set_item(PAM_USER) failed: '%s'",
658 pam_strerror(pamh, retval));
659 pam_passwd = NULL; /* Unset pam_passwd */
663 retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv);
665 if (retval != PAM_SUCCESS)
667 elog(LOG, "CheckPAMAuth: pam_set_item(PAM_CONV) failed: '%s'",
668 pam_strerror(pamh, retval));
669 pam_passwd = NULL; /* Unset pam_passwd */
673 retval = pam_authenticate(pamh, 0);
675 if (retval != PAM_SUCCESS)
677 elog(LOG, "CheckPAMAuth: pam_authenticate failed: '%s'",
678 pam_strerror(pamh, retval));
679 pam_passwd = NULL; /* Unset pam_passwd */
683 retval = pam_acct_mgmt(pamh, 0);
685 if (retval != PAM_SUCCESS)
687 elog(LOG, "CheckPAMAuth: pam_acct_mgmt failed: '%s'",
688 pam_strerror(pamh, retval));
689 pam_passwd = NULL; /* Unset pam_passwd */
693 retval = pam_end(pamh, retval);
695 if (retval != PAM_SUCCESS)
697 elog(LOG, "CheckPAMAuth: Failed to release PAM authenticator: '%s'",
698 pam_strerror(pamh, retval));
701 pam_passwd = NULL; /* Unset pam_passwd */
703 return (retval == PAM_SUCCESS ? STATUS_OK : STATUS_ERROR);
709 * Collect password response packet from frontend.
711 * Returns NULL if couldn't get password, else palloc'd string.
714 recv_password_packet(Port *port)
718 if (PG_PROTOCOL_MAJOR(port->proto) >= 3)
720 /* Expect 'p' message type */
723 mtype = pq_getbyte();
727 * If the client just disconnects without offering a password,
728 * don't make a log entry. This is legal per protocol spec and
729 * in fact commonly done by psql, so complaining just clutters
733 elog(COMMERROR, "Expected password response, got %c", mtype);
734 return NULL; /* EOF or bad message type */
739 /* For pre-3.0 clients, avoid log entry if they just disconnect */
740 if (pq_peekbyte() == EOF)
741 return NULL; /* EOF */
744 initStringInfo(&buf);
745 if (pq_getmessage(&buf, 1000)) /* receive password */
747 /* EOF - pq_getmessage already logged a suitable message */
753 * Apply sanity check: password packet length should agree with length
754 * of contained string. Note it is safe to use strlen here because
755 * StringInfo is guaranteed to have an appended '\0'.
757 if (strlen(buf.data) + 1 != buf.len)
758 elog(COMMERROR, "bogus password packet size");
760 /* Do not echo password to logs, for security. */
761 elog(DEBUG5, "received password packet");
764 * Return the received string. Note we do not attempt to do any
765 * character-set conversion on it; since we don't yet know the
766 * client's encoding, there wouldn't be much point.
773 * Called when we have sent an authorization request for a password.
774 * Get the response and check it.
777 recv_and_check_password_packet(Port *port)
782 passwd = recv_password_packet(port);
785 return STATUS_EOF; /* client wouldn't send password */
787 result = md5_crypt_verify(port, port->user_name, passwd);