1 /*-------------------------------------------------------------------------
4 * Routines to handle network authentication
6 * Portions Copyright (c) 1996-2005, 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.122 2005/01/12 21:37:53 tgl 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 *----------------------------------------------------------------
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__)
159 * pg_an_to_ln -- return the local name corresponding to an authentication
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.
172 pg_an_to_ln(char *aname)
176 if ((p = strchr(aname, '/')) || (p = strchr(aname, '@')))
183 * Various krb5 state which is not connection specfic, and a flag to
184 * indicate whether we have initialised it yet.
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;
195 krb5_error_code retval;
197 if (pg_krb5_initialised)
200 retval = krb5_init_context(&pg_krb5_context);
204 (errmsg("Kerberos initialization returned error %d",
206 com_err("postgres", retval, "while initializing krb5");
210 retval = krb5_kt_resolve(pg_krb5_context, pg_krb_server_keyfile, &pg_krb5_keytab);
214 (errmsg("Kerberos keytab resolving returned error %d",
216 com_err("postgres", retval, "while resolving keytab file \"%s\"",
217 pg_krb_server_keyfile);
218 krb5_free_context(pg_krb5_context);
222 retval = krb5_sname_to_principal(pg_krb5_context, NULL, PG_KRB_SRVNAM,
223 KRB5_NT_SRV_HST, &pg_krb5_server);
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\"",
232 krb5_kt_close(pg_krb5_context, pg_krb5_keytab);
233 krb5_free_context(pg_krb5_context);
237 pg_krb5_initialised = 1;
243 * pg_krb5_recvauth -- server routine to receive authentication information
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.
250 * We have our own keytab file because postgres is unlikely to run as root,
251 * and so cannot read the default keytab.
254 pg_krb5_recvauth(Port *port)
256 krb5_error_code retval;
258 krb5_auth_context auth_context = NULL;
262 ret = pg_krb5_init();
263 if (ret != STATUS_OK)
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);
272 (errmsg("Kerberos recvauth returned error %d",
274 com_err("postgres", retval, "from krb5_recvauth");
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.
283 * I have no idea why this is considered necessary.
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);
292 #error "bogus configuration"
297 (errmsg("Kerberos unparse_name returned error %d",
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);
305 kusername = pg_an_to_ln(kusername);
306 if (strncmp(port->user_name, kusername, SM_DATABASE_USER))
309 (errmsg("unexpected Kerberos user name received from client (received \"%s\", expected \"%s\")",
310 port->user_name, kusername)));
316 krb5_free_ticket(pg_krb5_context, ticket);
317 krb5_auth_con_free(pg_krb5_context, auth_context);
326 pg_krb5_recvauth(Port *port)
329 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
330 errmsg("Kerberos 5 not implemented on this server")));
337 * Tell the user the authentication failed, but not (much about) why.
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
345 * Note that many sorts of failure report additional information in the
346 * postmaster log, which we hope is only readable by good guys.
349 auth_failed(Port *port, int status)
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.)
363 if (status == STATUS_EOF)
366 switch (port->auth_method)
369 errstr = gettext_noop("authentication failed for user \"%s\": host rejected");
372 errstr = gettext_noop("Kerberos 4 authentication failed for user \"%s\"");
375 errstr = gettext_noop("Kerberos 5 authentication failed for user \"%s\"");
378 errstr = gettext_noop("\"trust\" authentication failed for user \"%s\"");
381 errstr = gettext_noop("Ident authentication failed for user \"%s\"");
386 errstr = gettext_noop("password authentication failed for user \"%s\"");
390 errstr = gettext_noop("PAM authentication failed for user \"%s\"");
394 errstr = gettext_noop("authentication failed for user \"%s\": invalid authentication method");
399 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
400 errmsg(errstr, port->user_name)));
406 * Client authentication starts here. If there is an error, this
407 * function does not return and the backend process is terminated.
410 ClientAuthentication(Port *port)
412 int status = STATUS_ERROR;
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.
420 if (hba_getauthmethod(port) != STATUS_OK)
422 (errcode(ERRCODE_CONFIG_FILE_ERROR),
423 errmsg("missing or erroneous pg_hba.conf file"),
424 errhint("See server log for details.")));
426 switch (port->auth_method)
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.
440 char hostinfo[NI_MAXHOST];
442 getnameinfo_all(&port->raddr.addr, port->raddr.salen,
443 hostinfo, sizeof(hostinfo),
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 ? gettext("SSL on") : gettext("SSL off"))));
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)));
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)
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);
474 sendAuthRequest(port, AUTH_REQ_KRB5);
475 status = pg_krb5_recvauth(port);
481 * If we are doing ident on unix-domain sockets, use SCM_CREDS
482 * only if it is defined and SO_PEERCRED isn't.
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)
489 #if defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED)
492 * Receive credentials on next message receipt, BSD/OS,
493 * NetBSD. We need to set this before the client sends the
498 if (setsockopt(port->sock, 0, LOCAL_CREDS, &on, sizeof(on)) < 0)
500 (errcode_for_socket_access(),
501 errmsg("could not enable credential reception: %m")));
504 sendAuthRequest(port, AUTH_REQ_SCM_CREDS);
507 status = authident(port);
511 sendAuthRequest(port, AUTH_REQ_MD5);
512 status = recv_and_check_password_packet(port);
516 sendAuthRequest(port, AUTH_REQ_CRYPT);
517 status = recv_and_check_password_packet(port);
521 sendAuthRequest(port, AUTH_REQ_PASSWORD);
522 status = recv_and_check_password_packet(port);
527 pam_port_cludge = port;
528 status = CheckPAMAuth(port, port->user_name, "");
537 if (status == STATUS_OK)
538 sendAuthRequest(port, AUTH_REQ_OK);
540 auth_failed(port, status);
545 * Send an authentication request packet to the frontend.
548 sendAuthRequest(Port *port, AuthRequest areq)
552 pq_beginmessage(&buf, 'R');
553 pq_sendint(&buf, (int32) areq, sizeof(int32));
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);
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.
567 if (areq != AUTH_REQ_OK)
575 * PAM conversation function
579 pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg,
580 struct pam_response ** resp, void *appdata_ptr)
582 if (num_msg != 1 || msg[0]->msg_style != PAM_PROMPT_ECHO_OFF)
584 switch (msg[0]->msg_style)
588 (errmsg("error from underlying PAM layer: %s",
593 (errmsg("unsupported PAM conversation %d/%s",
594 msg[0]->msg_style, msg[0]->msg)));
602 * Workaround for Solaris 2.6 where the PAM library is broken and
603 * does not pass appdata_ptr to the conversation routine
605 appdata_ptr = pam_passwd;
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.
612 if (strlen(appdata_ptr) == 0)
616 sendAuthRequest(pam_port_cludge, AUTH_REQ_PASSWORD);
617 passwd = recv_password_packet(pam_port_cludge);
620 return PAM_CONV_ERR; /* client didn't want to send password */
622 if (strlen(passwd) == 0)
625 (errmsg("empty password returned by client")));
628 appdata_ptr = passwd;
632 * Explicitly not using palloc here - PAM will free this memory in
635 *resp = calloc(num_msg, sizeof(struct pam_response));
639 (errcode(ERRCODE_OUT_OF_MEMORY),
640 errmsg("out of memory")));
644 (*resp)[0].resp = strdup((char *) appdata_ptr);
645 (*resp)[0].resp_retcode = 0;
647 return ((*resp)[0].resp ? PAM_SUCCESS : PAM_CONV_ERR);
652 * Check authentication against PAM.
655 CheckPAMAuth(Port *port, char *user, char *password)
658 pam_handle_t *pamh = NULL;
661 * Apparently, Solaris 2.6 is broken, and needs ugly static variable
664 pam_passwd = password;
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.
671 pam_passw_conv.appdata_ptr = (char *) password; /* from password above,
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);
679 retval = pam_start(PGSQL_PAM_SERVICE, "pgsql@",
680 &pam_passw_conv, &pamh);
682 if (retval != PAM_SUCCESS)
685 (errmsg("could not create PAM authenticator: %s",
686 pam_strerror(pamh, retval))));
687 pam_passwd = NULL; /* Unset pam_passwd */
691 retval = pam_set_item(pamh, PAM_USER, user);
693 if (retval != PAM_SUCCESS)
696 (errmsg("pam_set_item(PAM_USER) failed: %s",
697 pam_strerror(pamh, retval))));
698 pam_passwd = NULL; /* Unset pam_passwd */
702 retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv);
704 if (retval != PAM_SUCCESS)
707 (errmsg("pam_set_item(PAM_CONV) failed: %s",
708 pam_strerror(pamh, retval))));
709 pam_passwd = NULL; /* Unset pam_passwd */
713 retval = pam_authenticate(pamh, 0);
715 if (retval != PAM_SUCCESS)
718 (errmsg("pam_authenticate failed: %s",
719 pam_strerror(pamh, retval))));
720 pam_passwd = NULL; /* Unset pam_passwd */
724 retval = pam_acct_mgmt(pamh, 0);
726 if (retval != PAM_SUCCESS)
729 (errmsg("pam_acct_mgmt failed: %s",
730 pam_strerror(pamh, retval))));
731 pam_passwd = NULL; /* Unset pam_passwd */
735 retval = pam_end(pamh, retval);
737 if (retval != PAM_SUCCESS)
740 (errmsg("could not release PAM authenticator: %s",
741 pam_strerror(pamh, retval))));
744 pam_passwd = NULL; /* Unset pam_passwd */
746 return (retval == PAM_SUCCESS ? STATUS_OK : STATUS_ERROR);
752 * Collect password response packet from frontend.
754 * Returns NULL if couldn't get password, else palloc'd string.
757 recv_password_packet(Port *port)
761 if (PG_PROTOCOL_MAJOR(port->proto) >= 3)
763 /* Expect 'p' message type */
766 mtype = pq_getbyte();
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
777 (errcode(ERRCODE_PROTOCOL_VIOLATION),
778 errmsg("expected password response, got message type %d",
780 return NULL; /* EOF or bad message type */
785 /* For pre-3.0 clients, avoid log entry if they just disconnect */
786 if (pq_peekbyte() == EOF)
787 return NULL; /* EOF */
790 initStringInfo(&buf);
791 if (pq_getmessage(&buf, 1000)) /* receive password */
793 /* EOF - pq_getmessage already logged a suitable message */
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'.
803 if (strlen(buf.data) + 1 != buf.len)
805 (errcode(ERRCODE_PROTOCOL_VIOLATION),
806 errmsg("invalid password packet size")));
808 /* Do not echo password to logs, for security. */
810 (errmsg("received password packet")));
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.
822 * Called when we have sent an authorization request for a password.
823 * Get the response and check it.
826 recv_and_check_password_packet(Port *port)
831 passwd = recv_password_packet(port);
834 return STATUS_EOF; /* client wouldn't send password */
836 result = md5_crypt_verify(port, port->user_name, passwd);