1 /*-------------------------------------------------------------------------
4 * Routines to handle network authentication
6 * Portions Copyright (c) 1996-2004, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/libpq/auth.c,v 1.119 2004/10/12 21:54:38 petere 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)
113 (errmsg("Kerberos error: %s", krb_err_txt[status])));
116 if (strncmp(version, PG_KRB4_VERSION, KRB_SENDAUTH_VLEN) != 0)
119 (errmsg("unexpected Kerberos protocol version received from client (received \"%s\", expected \"%s\")",
120 version, PG_KRB4_VERSION)));
123 if (strncmp(port->user_name, auth_data.pname, SM_DATABASE_USER) != 0)
126 (errmsg("unexpected Kerberos user name received from client (received \"%s\", expected \"%s\")",
127 port->user_name, auth_data.pname)));
136 pg_krb4_recvauth(Port *port)
139 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
140 errmsg("Kerberos 4 not implemented on this server")));
147 /*----------------------------------------------------------------
148 * MIT Kerberos authentication system - protocol version 5
149 *----------------------------------------------------------------
156 * pg_an_to_ln -- return the local name corresponding to an authentication
159 * XXX Assumes that the first aname component is the user name. This is NOT
160 * necessarily so, since an aname can actually be something out of your
161 * worst X.400 nightmare, like
162 * ORGANIZATION=U. C. Berkeley/NAME=Paul M. Aoki@CS.BERKELEY.EDU
163 * Note that the MIT an_to_ln code does the same thing if you don't
164 * provide an aname mapping database...it may be a better idea to use
165 * krb5_an_to_ln, except that it punts if multiple components are found,
166 * and we can't afford to punt.
169 pg_an_to_ln(char *aname)
173 if ((p = strchr(aname, '/')) || (p = strchr(aname, '@')))
180 * Various krb5 state which is not connection specfic, and a flag to
181 * indicate whether we have initialised it yet.
183 static int pg_krb5_initialised;
184 static krb5_context pg_krb5_context;
185 static krb5_keytab pg_krb5_keytab;
186 static krb5_principal pg_krb5_server;
192 krb5_error_code retval;
194 if (pg_krb5_initialised)
197 retval = krb5_init_context(&pg_krb5_context);
201 (errmsg("Kerberos initialization returned error %d",
203 com_err("postgres", retval, "while initializing krb5");
207 retval = krb5_kt_resolve(pg_krb5_context, pg_krb_server_keyfile, &pg_krb5_keytab);
211 (errmsg("Kerberos keytab resolving returned error %d",
213 com_err("postgres", retval, "while resolving keytab file \"%s\"",
214 pg_krb_server_keyfile);
215 krb5_free_context(pg_krb5_context);
219 retval = krb5_sname_to_principal(pg_krb5_context, NULL, PG_KRB_SRVNAM,
220 KRB5_NT_SRV_HST, &pg_krb5_server);
224 (errmsg("Kerberos sname_to_principal(\"%s\") returned error %d",
225 PG_KRB_SRVNAM, retval)));
226 com_err("postgres", retval,
227 "while getting server principal for service \"%s\"",
229 krb5_kt_close(pg_krb5_context, pg_krb5_keytab);
230 krb5_free_context(pg_krb5_context);
234 pg_krb5_initialised = 1;
240 * pg_krb5_recvauth -- server routine to receive authentication information
243 * We still need to compare the username obtained from the client's setup
244 * packet to the authenticated name, as described in pg_krb4_recvauth. This
245 * is a bit more problematic in v5, as described above in pg_an_to_ln.
247 * We have our own keytab file because postgres is unlikely to run as root,
248 * and so cannot read the default keytab.
251 pg_krb5_recvauth(Port *port)
253 krb5_error_code retval;
255 krb5_auth_context auth_context = NULL;
259 ret = pg_krb5_init();
260 if (ret != STATUS_OK)
263 retval = krb5_recvauth(pg_krb5_context, &auth_context,
264 (krb5_pointer) & port->sock, PG_KRB_SRVNAM,
265 pg_krb5_server, 0, pg_krb5_keytab, &ticket);
269 (errmsg("Kerberos recvauth returned error %d",
271 com_err("postgres", retval, "from krb5_recvauth");
276 * The "client" structure comes out of the ticket and is therefore
277 * authenticated. Use it to check the username obtained from the
278 * postmaster startup packet.
280 * I have no idea why this is considered necessary.
282 #if defined(HAVE_KRB5_TICKET_ENC_PART2)
283 retval = krb5_unparse_name(pg_krb5_context,
284 ticket->enc_part2->client, &kusername);
285 #elif defined(HAVE_KRB5_TICKET_CLIENT)
286 retval = krb5_unparse_name(pg_krb5_context,
287 ticket->client, &kusername);
289 #error "bogus configuration"
294 (errmsg("Kerberos unparse_name returned error %d",
296 com_err("postgres", retval, "while unparsing client name");
297 krb5_free_ticket(pg_krb5_context, ticket);
298 krb5_auth_con_free(pg_krb5_context, auth_context);
302 kusername = pg_an_to_ln(kusername);
303 if (strncmp(port->user_name, kusername, SM_DATABASE_USER))
306 (errmsg("unexpected Kerberos user name received from client (received \"%s\", expected \"%s\")",
307 port->user_name, kusername)));
313 krb5_free_ticket(pg_krb5_context, ticket);
314 krb5_auth_con_free(pg_krb5_context, auth_context);
323 pg_krb5_recvauth(Port *port)
326 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
327 errmsg("Kerberos 5 not implemented on this server")));
334 * Tell the user the authentication failed, but not (much about) why.
336 * There is a tradeoff here between security concerns and making life
337 * unnecessarily difficult for legitimate users. We would not, for example,
338 * want to report the password we were expecting to receive...
339 * But it seems useful to report the username and authorization method
340 * in use, and these are items that must be presumed known to an attacker
342 * Note that many sorts of failure report additional information in the
343 * postmaster log, which we hope is only readable by good guys.
346 auth_failed(Port *port, int status)
351 * If we failed due to EOF from client, just quit; there's no point in
352 * trying to send a message to the client, and not much point in
353 * logging the failure in the postmaster log. (Logging the failure
354 * might be desirable, were it not for the fact that libpq closes the
355 * connection unceremoniously if challenged for a password when it
356 * hasn't got one to send. We'll get a useless log entry for every
357 * psql connection under password auth, even if it's perfectly
358 * successful, if we log STATUS_EOF events.)
360 if (status == STATUS_EOF)
363 switch (port->auth_method)
366 errstr = gettext_noop("authentication failed for user \"%s\": host rejected");
369 errstr = gettext_noop("Kerberos 4 authentication failed for user \"%s\"");
372 errstr = gettext_noop("Kerberos 5 authentication failed for user \"%s\"");
375 errstr = gettext_noop("\"trust\" authentication failed for user \"%s\"");
378 errstr = gettext_noop("Ident authentication failed for user \"%s\"");
383 errstr = gettext_noop("password authentication failed for user \"%s\"");
387 errstr = gettext_noop("PAM authentication failed for user \"%s\"");
391 errstr = gettext_noop("authentication failed for user \"%s\": invalid authentication method");
396 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
397 errmsg(errstr, port->user_name)));
403 * Client authentication starts here. If there is an error, this
404 * function does not return and the backend process is terminated.
407 ClientAuthentication(Port *port)
409 int status = STATUS_ERROR;
412 * Get the authentication method to use for this frontend/database
413 * combination. Note: a failure return indicates a problem with the
414 * hba config file, not with the request. hba.c should have dropped
415 * an error message into the postmaster logfile if it failed.
417 if (hba_getauthmethod(port) != STATUS_OK)
419 (errcode(ERRCODE_CONFIG_FILE_ERROR),
420 errmsg("missing or erroneous pg_hba.conf file"),
421 errhint("See server log for details.")));
423 switch (port->auth_method)
428 * This could have come from an explicit "reject" entry in
429 * pg_hba.conf, but more likely it means there was no matching
430 * entry. Take pity on the poor user and issue a helpful
431 * error message. NOTE: this is not a security breach,
432 * because all the info reported here is known at the frontend
433 * and must be assumed known to bad guys. We're merely helping
434 * out the less clueful good guys.
437 char hostinfo[NI_MAXHOST];
439 getnameinfo_all(&port->raddr.addr, port->raddr.salen,
440 hostinfo, sizeof(hostinfo),
446 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
447 errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\", %s",
448 hostinfo, port->user_name, port->database_name,
449 port->ssl ? gettext("SSL on") : gettext("SSL off"))));
452 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
453 errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\"",
454 hostinfo, port->user_name, port->database_name)));
460 /* Kerberos 4 only seems to work with AF_INET. */
461 if (port->raddr.addr.ss_family != AF_INET
462 || port->laddr.addr.ss_family != AF_INET)
464 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
465 errmsg("Kerberos 4 only supports IPv4 connections")));
466 sendAuthRequest(port, AUTH_REQ_KRB4);
467 status = pg_krb4_recvauth(port);
471 sendAuthRequest(port, AUTH_REQ_KRB5);
472 status = pg_krb5_recvauth(port);
478 * If we are doing ident on unix-domain sockets, use SCM_CREDS
479 * only if it is defined and SO_PEERCRED isn't.
481 #if !defined(HAVE_GETPEEREID) && !defined(SO_PEERCRED) && \
482 (defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || \
483 (defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS)))
484 if (port->raddr.addr.ss_family == AF_UNIX)
486 #if defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED)
489 * Receive credentials on next message receipt, BSD/OS,
490 * NetBSD. We need to set this before the client sends the
495 if (setsockopt(port->sock, 0, LOCAL_CREDS, &on, sizeof(on)) < 0)
497 (errcode_for_socket_access(),
498 errmsg("could not enable credential reception: %m")));
501 sendAuthRequest(port, AUTH_REQ_SCM_CREDS);
504 status = authident(port);
508 sendAuthRequest(port, AUTH_REQ_MD5);
509 status = recv_and_check_password_packet(port);
513 sendAuthRequest(port, AUTH_REQ_CRYPT);
514 status = recv_and_check_password_packet(port);
518 sendAuthRequest(port, AUTH_REQ_PASSWORD);
519 status = recv_and_check_password_packet(port);
524 pam_port_cludge = port;
525 status = CheckPAMAuth(port, port->user_name, "");
534 if (status == STATUS_OK)
535 sendAuthRequest(port, AUTH_REQ_OK);
537 auth_failed(port, status);
542 * Send an authentication request packet to the frontend.
545 sendAuthRequest(Port *port, AuthRequest areq)
549 pq_beginmessage(&buf, 'R');
550 pq_sendint(&buf, (int32) areq, sizeof(int32));
552 /* Add the salt for encrypted passwords. */
553 if (areq == AUTH_REQ_MD5)
554 pq_sendbytes(&buf, port->md5Salt, 4);
555 else if (areq == AUTH_REQ_CRYPT)
556 pq_sendbytes(&buf, port->cryptSalt, 2);
561 * Flush message so client will see it, except for AUTH_REQ_OK, which
562 * need not be sent until we are ready for queries.
564 if (areq != AUTH_REQ_OK)
572 * PAM conversation function
576 pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg,
577 struct pam_response ** resp, void *appdata_ptr)
579 if (num_msg != 1 || msg[0]->msg_style != PAM_PROMPT_ECHO_OFF)
581 switch (msg[0]->msg_style)
585 (errmsg("error from underlying PAM layer: %s",
590 (errmsg("unsupported PAM conversation %d/%s",
591 msg[0]->msg_style, msg[0]->msg)));
599 * Workaround for Solaris 2.6 where the PAM library is broken and
600 * does not pass appdata_ptr to the conversation routine
602 appdata_ptr = pam_passwd;
606 * Password wasn't passed to PAM the first time around - let's go ask
607 * the client to send a password, which we then stuff into PAM.
609 if (strlen(appdata_ptr) == 0)
613 sendAuthRequest(pam_port_cludge, AUTH_REQ_PASSWORD);
614 passwd = recv_password_packet(pam_port_cludge);
617 return PAM_CONV_ERR; /* client didn't want to send password */
619 if (strlen(passwd) == 0)
622 (errmsg("empty password returned by client")));
625 appdata_ptr = passwd;
629 * Explicitly not using palloc here - PAM will free this memory in
632 *resp = calloc(num_msg, sizeof(struct pam_response));
636 (errcode(ERRCODE_OUT_OF_MEMORY),
637 errmsg("out of memory")));
641 (*resp)[0].resp = strdup((char *) appdata_ptr);
642 (*resp)[0].resp_retcode = 0;
644 return ((*resp)[0].resp ? PAM_SUCCESS : PAM_CONV_ERR);
649 * Check authentication against PAM.
652 CheckPAMAuth(Port *port, char *user, char *password)
655 pam_handle_t *pamh = NULL;
658 * Apparently, Solaris 2.6 is broken, and needs ugly static variable
661 pam_passwd = password;
664 * Set the application data portion of the conversation struct This is
665 * later used inside the PAM conversation to pass the password to the
666 * authentication module.
668 pam_passw_conv.appdata_ptr = (char *) password; /* from password above,
671 /* Optionally, one can set the service name in pg_hba.conf */
672 if (port->auth_arg && port->auth_arg[0] != '\0')
673 retval = pam_start(port->auth_arg, "pgsql@",
674 &pam_passw_conv, &pamh);
676 retval = pam_start(PGSQL_PAM_SERVICE, "pgsql@",
677 &pam_passw_conv, &pamh);
679 if (retval != PAM_SUCCESS)
682 (errmsg("could not create PAM authenticator: %s",
683 pam_strerror(pamh, retval))));
684 pam_passwd = NULL; /* Unset pam_passwd */
688 retval = pam_set_item(pamh, PAM_USER, user);
690 if (retval != PAM_SUCCESS)
693 (errmsg("pam_set_item(PAM_USER) failed: %s",
694 pam_strerror(pamh, retval))));
695 pam_passwd = NULL; /* Unset pam_passwd */
699 retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv);
701 if (retval != PAM_SUCCESS)
704 (errmsg("pam_set_item(PAM_CONV) failed: %s",
705 pam_strerror(pamh, retval))));
706 pam_passwd = NULL; /* Unset pam_passwd */
710 retval = pam_authenticate(pamh, 0);
712 if (retval != PAM_SUCCESS)
715 (errmsg("pam_authenticate failed: %s",
716 pam_strerror(pamh, retval))));
717 pam_passwd = NULL; /* Unset pam_passwd */
721 retval = pam_acct_mgmt(pamh, 0);
723 if (retval != PAM_SUCCESS)
726 (errmsg("pam_acct_mgmt failed: %s",
727 pam_strerror(pamh, retval))));
728 pam_passwd = NULL; /* Unset pam_passwd */
732 retval = pam_end(pamh, retval);
734 if (retval != PAM_SUCCESS)
737 (errmsg("could not release PAM authenticator: %s",
738 pam_strerror(pamh, retval))));
741 pam_passwd = NULL; /* Unset pam_passwd */
743 return (retval == PAM_SUCCESS ? STATUS_OK : STATUS_ERROR);
749 * Collect password response packet from frontend.
751 * Returns NULL if couldn't get password, else palloc'd string.
754 recv_password_packet(Port *port)
758 if (PG_PROTOCOL_MAJOR(port->proto) >= 3)
760 /* Expect 'p' message type */
763 mtype = pq_getbyte();
767 * If the client just disconnects without offering a password,
768 * don't make a log entry. This is legal per protocol spec
769 * and in fact commonly done by psql, so complaining just
774 (errcode(ERRCODE_PROTOCOL_VIOLATION),
775 errmsg("expected password response, got message type %d",
777 return NULL; /* EOF or bad message type */
782 /* For pre-3.0 clients, avoid log entry if they just disconnect */
783 if (pq_peekbyte() == EOF)
784 return NULL; /* EOF */
787 initStringInfo(&buf);
788 if (pq_getmessage(&buf, 1000)) /* receive password */
790 /* EOF - pq_getmessage already logged a suitable message */
796 * Apply sanity check: password packet length should agree with length
797 * of contained string. Note it is safe to use strlen here because
798 * StringInfo is guaranteed to have an appended '\0'.
800 if (strlen(buf.data) + 1 != buf.len)
802 (errcode(ERRCODE_PROTOCOL_VIOLATION),
803 errmsg("invalid password packet size")));
805 /* Do not echo password to logs, for security. */
807 (errmsg("received password packet")));
810 * Return the received string. Note we do not attempt to do any
811 * character-set conversion on it; since we don't yet know the
812 * client's encoding, there wouldn't be much point.
819 * Called when we have sent an authorization request for a password.
820 * Get the response and check it.
823 recv_and_check_password_packet(Port *port)
828 passwd = recv_password_packet(port);
831 return STATUS_EOF; /* client wouldn't send password */
833 result = md5_crypt_verify(port, port->user_name, passwd);