Commit 26e6991a authored by Magnus Hagander's avatar Magnus Hagander

Rearrange the code in auth.c so that all functions for a single authentication

method is grouped together in a reasonably similar way, keeping the "global
shared functions" together in their own section as well. Makes it a lot easier
to find your way around the code.
parent c30c1b87
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/libpq/auth.c,v 1.166 2008/08/01 09:09:49 mha Exp $ * $PostgreSQL: pgsql/src/backend/libpq/auth.c,v 1.167 2008/08/01 11:41:12 mha Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
...@@ -32,25 +32,33 @@ ...@@ -32,25 +32,33 @@
#include "libpq/pqformat.h" #include "libpq/pqformat.h"
#include "storage/ipc.h" #include "storage/ipc.h"
/*----------------------------------------------------------------
* Global authentication functions
*----------------------------------------------------------------
*/
static void sendAuthRequest(Port *port, AuthRequest areq); static void sendAuthRequest(Port *port, AuthRequest areq);
static void auth_failed(Port *port, int status); static void auth_failed(Port *port, int status);
static char *recv_password_packet(Port *port); static char *recv_password_packet(Port *port);
static int recv_and_check_password_packet(Port *port); static int recv_and_check_password_packet(Port *port);
static int authident(hbaPort *port);
char *pg_krb_server_keyfile;
char *pg_krb_srvnam;
bool pg_krb_caseins_users;
char *pg_krb_server_hostname = NULL;
char *pg_krb_realm = NULL;
/*----------------------------------------------------------------
* Ident authentication
*----------------------------------------------------------------
*/
/* Max size of username ident server can return */ /* Max size of username ident server can return */
#define IDENT_USERNAME_MAX 512 #define IDENT_USERNAME_MAX 512
/* Standard TCP port number for Ident service. Assigned by IANA */ /* Standard TCP port number for Ident service. Assigned by IANA */
#define IDENT_PORT 113 #define IDENT_PORT 113
static int authident(hbaPort *port);
/*----------------------------------------------------------------
* PAM authentication
*----------------------------------------------------------------
*/
#ifdef USE_PAM #ifdef USE_PAM
#ifdef HAVE_PAM_PAM_APPL_H #ifdef HAVE_PAM_PAM_APPL_H
#include <pam/pam_appl.h> #include <pam/pam_appl.h>
...@@ -75,6 +83,11 @@ static Port *pam_port_cludge; /* Workaround for passing "Port *port" into ...@@ -75,6 +83,11 @@ static Port *pam_port_cludge; /* Workaround for passing "Port *port" into
* pam_passwd_conv_proc */ * pam_passwd_conv_proc */
#endif /* USE_PAM */ #endif /* USE_PAM */
/*----------------------------------------------------------------
* LDAP authentication
*----------------------------------------------------------------
*/
#ifdef USE_LDAP #ifdef USE_LDAP
#ifndef WIN32 #ifndef WIN32
/* We use a deprecated function to keep the codepath the same as win32. */ /* We use a deprecated function to keep the codepath the same as win32. */
...@@ -95,21 +108,33 @@ ULONG(*__ldap_start_tls_sA) ( ...@@ -95,21 +108,33 @@ ULONG(*__ldap_start_tls_sA) (
#endif #endif
static int CheckLDAPAuth(Port *port); static int CheckLDAPAuth(Port *port);
#endif #endif /* USE_LDAP */
/*----------------------------------------------------------------
* Kerberos and GSSAPI GUCs
*----------------------------------------------------------------
*/
char *pg_krb_server_keyfile;
char *pg_krb_srvnam;
bool pg_krb_caseins_users;
char *pg_krb_server_hostname = NULL;
char *pg_krb_realm = NULL;
#ifdef KRB5
/*---------------------------------------------------------------- /*----------------------------------------------------------------
* MIT Kerberos authentication system - protocol version 5 * MIT Kerberos authentication system - protocol version 5
*---------------------------------------------------------------- *----------------------------------------------------------------
*/ */
static int pg_krb5_recvauth(Port *port);
#ifdef KRB5
#include <krb5.h> #include <krb5.h>
/* Some old versions of Kerberos do not include <com_err.h> in <krb5.h> */ /* Some old versions of Kerberos do not include <com_err.h> in <krb5.h> */
#if !defined(__COM_ERR_H) && !defined(__COM_ERR_H__) #if !defined(__COM_ERR_H) && !defined(__COM_ERR_H__)
#include <com_err.h> #include <com_err.h>
#endif #endif
/* /*
* Various krb5 state which is not connection specfic, and a flag to * Various krb5 state which is not connection specfic, and a flag to
* indicate whether we have initialised it yet. * indicate whether we have initialised it yet.
...@@ -118,600 +143,738 @@ static int pg_krb5_initialised; ...@@ -118,600 +143,738 @@ static int pg_krb5_initialised;
static krb5_context pg_krb5_context; static krb5_context pg_krb5_context;
static krb5_keytab pg_krb5_keytab; static krb5_keytab pg_krb5_keytab;
static krb5_principal pg_krb5_server; static krb5_principal pg_krb5_server;
#endif /* KRB5 */
static int /*----------------------------------------------------------------
pg_krb5_init(void) * GSSAPI Authentication
{ *----------------------------------------------------------------
krb5_error_code retval; */
char *khostname; static int pg_GSS_recvauth(Port *port);
if (pg_krb5_initialised) #ifdef ENABLE_GSS
return STATUS_OK; #if defined(HAVE_GSSAPI_H)
#include <gssapi.h>
#else
#include <gssapi/gssapi.h>
#endif
#endif /* ENABLE_GSS */
retval = krb5_init_context(&pg_krb5_context);
if (retval)
{
ereport(LOG,
(errmsg("Kerberos initialization returned error %d",
retval)));
com_err("postgres", retval, "while initializing krb5");
return STATUS_ERROR;
}
retval = krb5_kt_resolve(pg_krb5_context, pg_krb_server_keyfile, &pg_krb5_keytab); /*----------------------------------------------------------------
if (retval) * SSPI Authentication
{ *----------------------------------------------------------------
ereport(LOG, */
(errmsg("Kerberos keytab resolving returned error %d", static int pg_SSPI_recvauth(Port *port);
retval)));
com_err("postgres", retval, "while resolving keytab file \"%s\"", #ifdef ENABLE_SSPI
pg_krb_server_keyfile); typedef SECURITY_STATUS
krb5_free_context(pg_krb5_context); (WINAPI * QUERY_SECURITY_CONTEXT_TOKEN_FN) (
return STATUS_ERROR; PCtxtHandle, void **);
} #endif
/*----------------------------------------------------------------
* Global authentication functions
*----------------------------------------------------------------
*/
/*
* Tell the user the authentication failed, but not (much about) why.
*
* There is a tradeoff here between security concerns and making life
* unnecessarily difficult for legitimate users. We would not, for example,
* want to report the password we were expecting to receive...
* But it seems useful to report the username and authorization method
* in use, and these are items that must be presumed known to an attacker
* anyway.
* Note that many sorts of failure report additional information in the
* postmaster log, which we hope is only readable by good guys.
*/
static void
auth_failed(Port *port, int status)
{
const char *errstr;
/* /*
* If no hostname was specified, pg_krb_server_hostname is already NULL. * If we failed due to EOF from client, just quit; there's no point in
* If it's set to blank, force it to NULL. * trying to send a message to the client, and not much point in logging
* the failure in the postmaster log. (Logging the failure might be
* desirable, were it not for the fact that libpq closes the connection
* unceremoniously if challenged for a password when it hasn't got one to
* send. We'll get a useless log entry for every psql connection under
* password auth, even if it's perfectly successful, if we log STATUS_EOF
* events.)
*/ */
khostname = pg_krb_server_hostname; if (status == STATUS_EOF)
if (khostname && khostname[0] == '\0') proc_exit(0);
khostname = NULL;
retval = krb5_sname_to_principal(pg_krb5_context, switch (port->auth_method)
khostname,
pg_krb_srvnam,
KRB5_NT_SRV_HST,
&pg_krb5_server);
if (retval)
{ {
ereport(LOG, case uaReject:
(errmsg("Kerberos sname_to_principal(\"%s\", \"%s\") returned error %d", errstr = gettext_noop("authentication failed for user \"%s\": host rejected");
khostname ? khostname : "server hostname", pg_krb_srvnam, retval))); break;
com_err("postgres", retval, case uaKrb5:
"while getting server principal for server \"%s\" for service \"%s\"", errstr = gettext_noop("Kerberos 5 authentication failed for user \"%s\"");
khostname ? khostname : "server hostname", pg_krb_srvnam); break;
krb5_kt_close(pg_krb5_context, pg_krb5_keytab); case uaGSS:
krb5_free_context(pg_krb5_context); errstr = gettext_noop("GSSAPI authentication failed for user \"%s\"");
return STATUS_ERROR; break;
case uaSSPI:
errstr = gettext_noop("SSPI authentication failed for user \"%s\"");
break;
case uaTrust:
errstr = gettext_noop("\"trust\" authentication failed for user \"%s\"");
break;
case uaIdent:
errstr = gettext_noop("Ident authentication failed for user \"%s\"");
break;
case uaMD5:
case uaCrypt:
case uaPassword:
errstr = gettext_noop("password authentication failed for user \"%s\"");
break;
#ifdef USE_PAM
case uaPAM:
errstr = gettext_noop("PAM authentication failed for user \"%s\"");
break;
#endif /* USE_PAM */
#ifdef USE_LDAP
case uaLDAP:
errstr = gettext_noop("LDAP authentication failed for user \"%s\"");
break;
#endif /* USE_LDAP */
default:
errstr = gettext_noop("authentication failed for user \"%s\": invalid authentication method");
break;
} }
pg_krb5_initialised = 1; ereport(FATAL,
return STATUS_OK; (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg(errstr, port->user_name)));
/* doesn't return */
} }
/* /*
* pg_krb5_recvauth -- server routine to receive authentication information * Client authentication starts here. If there is an error, this
* from the client * function does not return and the backend process is terminated.
*
* We still need to compare the username obtained from the client's setup
* packet to the authenticated name.
*
* We have our own keytab file because postgres is unlikely to run as root,
* and so cannot read the default keytab.
*/ */
static int void
pg_krb5_recvauth(Port *port) ClientAuthentication(Port *port)
{ {
krb5_error_code retval; int status = STATUS_ERROR;
int ret;
krb5_auth_context auth_context = NULL;
krb5_ticket *ticket;
char *kusername;
char *cp;
if (get_role_line(port->user_name) == NULL)
return STATUS_ERROR;
ret = pg_krb5_init(); /*
if (ret != STATUS_OK) * Get the authentication method to use for this frontend/database
return ret; * combination. Note: a failure return indicates a problem with the hba
* config file, not with the request. hba.c should have dropped an error
* message into the postmaster logfile if it failed.
*/
if (hba_getauthmethod(port) != STATUS_OK)
ereport(FATAL,
(errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("missing or erroneous pg_hba.conf file"),
errhint("See server log for details.")));
retval = krb5_recvauth(pg_krb5_context, &auth_context, switch (port->auth_method)
(krb5_pointer) & port->sock, pg_krb_srvnam,
pg_krb5_server, 0, pg_krb5_keytab, &ticket);
if (retval)
{ {
ereport(LOG, case uaReject:
(errmsg("Kerberos recvauth returned error %d",
retval)));
com_err("postgres", retval, "from krb5_recvauth");
return STATUS_ERROR;
}
/* /*
* The "client" structure comes out of the ticket and is therefore * This could have come from an explicit "reject" entry in
* authenticated. Use it to check the username obtained from the * pg_hba.conf, but more likely it means there was no matching
* postmaster startup packet. * entry. Take pity on the poor user and issue a helpful error
* message. NOTE: this is not a security breach, because all the
* info reported here is known at the frontend and must be assumed
* known to bad guys. We're merely helping out the less clueful
* good guys.
*/ */
#if defined(HAVE_KRB5_TICKET_ENC_PART2)
retval = krb5_unparse_name(pg_krb5_context,
ticket->enc_part2->client, &kusername);
#elif defined(HAVE_KRB5_TICKET_CLIENT)
retval = krb5_unparse_name(pg_krb5_context,
ticket->client, &kusername);
#else
#error "bogus configuration"
#endif
if (retval)
{ {
ereport(LOG, char hostinfo[NI_MAXHOST];
(errmsg("Kerberos unparse_name returned error %d",
retval))); pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
com_err("postgres", retval, "while unparsing client name"); hostinfo, sizeof(hostinfo),
krb5_free_ticket(pg_krb5_context, ticket); NULL, 0,
krb5_auth_con_free(pg_krb5_context, auth_context); NI_NUMERICHOST);
return STATUS_ERROR;
#ifdef USE_SSL
ereport(FATAL,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\", %s",
hostinfo, port->user_name, port->database_name,
port->ssl ? _("SSL on") : _("SSL off"))));
#else
ereport(FATAL,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\"",
hostinfo, port->user_name, port->database_name)));
#endif
break;
} }
cp = strchr(kusername, '@'); case uaKrb5:
if (cp) sendAuthRequest(port, AUTH_REQ_KRB5);
{ status = pg_krb5_recvauth(port);
*cp = '\0'; break;
cp++;
if (pg_krb_realm != NULL && strlen(pg_krb_realm)) case uaGSS:
{ sendAuthRequest(port, AUTH_REQ_GSS);
/* Match realm against configured */ status = pg_GSS_recvauth(port);
if (pg_krb_caseins_users) break;
ret = pg_strcasecmp(pg_krb_realm, cp);
else
ret = strcmp(pg_krb_realm, cp);
if (ret) case uaSSPI:
{ sendAuthRequest(port, AUTH_REQ_SSPI);
elog(DEBUG2, status = pg_SSPI_recvauth(port);
"krb5 realm (%s) and configured realm (%s) don't match", break;
cp, pg_krb_realm);
krb5_free_ticket(pg_krb5_context, ticket); case uaIdent:
krb5_auth_con_free(pg_krb5_context, auth_context);
return STATUS_ERROR; /*
} * If we are doing ident on unix-domain sockets, use SCM_CREDS
} * only if it is defined and SO_PEERCRED isn't.
} */
else if (pg_krb_realm && strlen(pg_krb_realm)) #if !defined(HAVE_GETPEEREID) && !defined(SO_PEERCRED) && \
(defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || \
(defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS)))
if (port->raddr.addr.ss_family == AF_UNIX)
{ {
elog(DEBUG2, #if defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED)
"krb5 did not return realm but realm matching was requested");
krb5_free_ticket(pg_krb5_context, ticket); /*
krb5_auth_con_free(pg_krb5_context, auth_context); * Receive credentials on next message receipt, BSD/OS,
return STATUS_ERROR; * NetBSD. We need to set this before the client sends the
} * next packet.
*/
int on = 1;
if (pg_krb_caseins_users) if (setsockopt(port->sock, 0, LOCAL_CREDS, &on, sizeof(on)) < 0)
ret = pg_strncasecmp(port->user_name, kusername, SM_DATABASE_USER); ereport(FATAL,
else (errcode_for_socket_access(),
ret = strncmp(port->user_name, kusername, SM_DATABASE_USER); errmsg("could not enable credential reception: %m")));
if (ret) #endif
{
ereport(LOG,
(errmsg("unexpected Kerberos user name received from client (received \"%s\", expected \"%s\")",
port->user_name, kusername)));
ret = STATUS_ERROR;
}
else
ret = STATUS_OK;
krb5_free_ticket(pg_krb5_context, ticket); sendAuthRequest(port, AUTH_REQ_SCM_CREDS);
krb5_auth_con_free(pg_krb5_context, auth_context); }
free(kusername); #endif
status = authident(port);
break;
return ret; case uaMD5:
} sendAuthRequest(port, AUTH_REQ_MD5);
#else status = recv_and_check_password_packet(port);
break;
static int case uaCrypt:
pg_krb5_recvauth(Port *port) sendAuthRequest(port, AUTH_REQ_CRYPT);
{ status = recv_and_check_password_packet(port);
ereport(LOG, break;
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("Kerberos 5 not implemented on this server")));
return STATUS_ERROR;
}
#endif /* KRB5 */
/*---------------------------------------------------------------- case uaPassword:
* GSSAPI authentication system sendAuthRequest(port, AUTH_REQ_PASSWORD);
*---------------------------------------------------------------- status = recv_and_check_password_packet(port);
*/ break;
#ifdef ENABLE_GSS #ifdef USE_PAM
case uaPAM:
pam_port_cludge = port;
status = CheckPAMAuth(port, port->user_name, "");
break;
#endif /* USE_PAM */
#if defined(HAVE_GSSAPI_H) #ifdef USE_LDAP
#include <gssapi.h> case uaLDAP:
#else status = CheckLDAPAuth(port);
#include <gssapi/gssapi.h> break;
#endif #endif
#if defined(WIN32) && !defined(WIN32_ONLY_COMPILER) case uaTrust:
/* status = STATUS_OK;
* MIT Kerberos GSSAPI DLL doesn't properly export the symbols for MingW break;
* that contain the OIDs required. Redefine here, values copied }
* from src/athena/auth/krb5/src/lib/gssapi/generic/gssapi_generic.c
*/ if (status == STATUS_OK)
static const gss_OID_desc GSS_C_NT_USER_NAME_desc = sendAuthRequest(port, AUTH_REQ_OK);
{10, (void *) "\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x02"}; else
static GSS_DLLIMP gss_OID GSS_C_NT_USER_NAME = &GSS_C_NT_USER_NAME_desc; auth_failed(port, status);
#endif }
/*
* Send an authentication request packet to the frontend.
*/
static void static void
pg_GSS_error(int severity, char *errmsg, OM_uint32 maj_stat, OM_uint32 min_stat) sendAuthRequest(Port *port, AuthRequest areq)
{ {
gss_buffer_desc gmsg; StringInfoData buf;
OM_uint32 lmaj_s,
lmin_s,
msg_ctx;
char msg_major[128],
msg_minor[128];
/* Fetch major status message */ pq_beginmessage(&buf, 'R');
msg_ctx = 0; pq_sendint(&buf, (int32) areq, sizeof(int32));
lmaj_s = gss_display_status(&lmin_s, maj_stat, GSS_C_GSS_CODE,
GSS_C_NO_OID, &msg_ctx, &gmsg);
strlcpy(msg_major, gmsg.value, sizeof(msg_major));
gss_release_buffer(&lmin_s, &gmsg);
if (msg_ctx) /* Add the salt for encrypted passwords. */
if (areq == AUTH_REQ_MD5)
pq_sendbytes(&buf, port->md5Salt, 4);
else if (areq == AUTH_REQ_CRYPT)
pq_sendbytes(&buf, port->cryptSalt, 2);
#if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
/* /*
* More than one message available. XXX: Should we loop and read all * Add the authentication data for the next step of the GSSAPI or SSPI
* messages? (same below) * negotiation.
*/ */
ereport(WARNING, else if (areq == AUTH_REQ_GSS_CONT)
(errmsg_internal("incomplete GSS error report"))); {
if (port->gss->outbuf.length > 0)
{
elog(DEBUG4, "sending GSS token of length %u",
(unsigned int) port->gss->outbuf.length);
/* Fetch mechanism minor status message */ pq_sendbytes(&buf, port->gss->outbuf.value, port->gss->outbuf.length);
msg_ctx = 0; }
lmaj_s = gss_display_status(&lmin_s, min_stat, GSS_C_MECH_CODE, }
GSS_C_NO_OID, &msg_ctx, &gmsg); #endif
strlcpy(msg_minor, gmsg.value, sizeof(msg_minor));
gss_release_buffer(&lmin_s, &gmsg);
if (msg_ctx) pq_endmessage(&buf);
ereport(WARNING,
(errmsg_internal("incomplete GSS minor error report")));
/* /*
* errmsg_internal, since translation of the first part must be done * Flush message so client will see it, except for AUTH_REQ_OK, which need
* before calling this function anyway. * not be sent until we are ready for queries.
*/ */
ereport(severity, if (areq != AUTH_REQ_OK)
(errmsg_internal("%s", errmsg), pq_flush();
errdetail("%s: %s", msg_major, msg_minor)));
} }
static int /*
pg_GSS_recvauth(Port *port) * Collect password response packet from frontend.
*
* Returns NULL if couldn't get password, else palloc'd string.
*/
static char *
recv_password_packet(Port *port)
{ {
OM_uint32 maj_stat,
min_stat,
lmin_s,
gflags;
int mtype;
int ret;
StringInfoData buf; StringInfoData buf;
gss_buffer_desc gbuf;
/* if (PG_PROTOCOL_MAJOR(port->proto) >= 3)
* GSS auth is not supported for protocol versions before 3, because it
* relies on the overall message length word to determine the GSS payload
* size in AuthenticationGSSContinue and PasswordMessage messages.
* (This is, in fact, a design error in our GSS support, because protocol
* messages are supposed to be parsable without relying on the length
* word; but it's not worth changing it now.)
*/
if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
ereport(FATAL,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("GSSAPI is not supported in protocol version 2")));
if (pg_krb_server_keyfile && strlen(pg_krb_server_keyfile) > 0)
{
/*
* Set default Kerberos keytab file for the Krb5 mechanism.
*
* setenv("KRB5_KTNAME", pg_krb_server_keyfile, 0); except setenv()
* not always available.
*/
if (getenv("KRB5_KTNAME") == NULL)
{
size_t kt_len = strlen(pg_krb_server_keyfile) + 14;
char *kt_path = malloc(kt_len);
if (!kt_path)
{ {
ereport(LOG, /* Expect 'p' message type */
(errcode(ERRCODE_OUT_OF_MEMORY), int mtype;
errmsg("out of memory")));
return STATUS_ERROR;
}
snprintf(kt_path, kt_len, "KRB5_KTNAME=%s", pg_krb_server_keyfile);
putenv(kt_path);
}
}
/*
* We accept any service principal that's present in our keytab. This
* increases interoperability between kerberos implementations that see
* for example case sensitivity differently, while not really opening up
* any vector of attack.
*/
port->gss->cred = GSS_C_NO_CREDENTIAL;
/*
* Initialize sequence with an empty context
*/
port->gss->ctx = GSS_C_NO_CONTEXT;
/*
* Loop through GSSAPI message exchange. This exchange can consist of
* multiple messags sent in both directions. First message is always from
* the client. All messages from client to server are password packets
* (type 'p').
*/
do
{
mtype = pq_getbyte(); mtype = pq_getbyte();
if (mtype != 'p') if (mtype != 'p')
{ {
/* Only log error if client didn't disconnect. */ /*
* If the client just disconnects without offering a password,
* don't make a log entry. This is legal per protocol spec and in
* fact commonly done by psql, so complaining just clutters the
* log.
*/
if (mtype != EOF) if (mtype != EOF)
ereport(COMMERROR, ereport(COMMERROR,
(errcode(ERRCODE_PROTOCOL_VIOLATION), (errcode(ERRCODE_PROTOCOL_VIOLATION),
errmsg("expected GSS response, got message type %d", errmsg("expected password response, got message type %d",
mtype))); mtype)));
return STATUS_ERROR; return NULL; /* EOF or bad message type */
}
}
else
{
/* For pre-3.0 clients, avoid log entry if they just disconnect */
if (pq_peekbyte() == EOF)
return NULL; /* EOF */
} }
/* Get the actual GSS token */
initStringInfo(&buf); initStringInfo(&buf);
if (pq_getmessage(&buf, 2000)) if (pq_getmessage(&buf, 1000)) /* receive password */
{ {
/* EOF - pq_getmessage already logged error */ /* EOF - pq_getmessage already logged a suitable message */
pfree(buf.data); pfree(buf.data);
return STATUS_ERROR; return NULL;
} }
/* Map to GSSAPI style buffer */ /*
gbuf.length = buf.len; * Apply sanity check: password packet length should agree with length of
gbuf.value = buf.data; * contained string. Note it is safe to use strlen here because
* StringInfo is guaranteed to have an appended '\0'.
elog(DEBUG4, "Processing received GSS token of length %u", */
(unsigned int) gbuf.length); if (strlen(buf.data) + 1 != buf.len)
ereport(COMMERROR,
maj_stat = gss_accept_sec_context( (errcode(ERRCODE_PROTOCOL_VIOLATION),
&min_stat, errmsg("invalid password packet size")));
&port->gss->ctx,
port->gss->cred,
&gbuf,
GSS_C_NO_CHANNEL_BINDINGS,
&port->gss->name,
NULL,
&port->gss->outbuf,
&gflags,
NULL,
NULL);
/* gbuf no longer used */
pfree(buf.data);
elog(DEBUG5, "gss_accept_sec_context major: %d, " /* Do not echo password to logs, for security. */
"minor: %d, outlen: %u, outflags: %x", ereport(DEBUG5,
maj_stat, min_stat, (errmsg("received password packet")));
(unsigned int) port->gss->outbuf.length, gflags);
if (port->gss->outbuf.length != 0)
{
/* /*
* Negotiation generated data to be sent to the client. * Return the received string. Note we do not attempt to do any
* character-set conversion on it; since we don't yet know the client's
* encoding, there wouldn't be much point.
*/ */
OM_uint32 lmin_s; return buf.data;
}
elog(DEBUG4, "sending GSS response token of length %u",
(unsigned int) port->gss->outbuf.length);
sendAuthRequest(port, AUTH_REQ_GSS_CONT); /*----------------------------------------------------------------
* MD5 and crypt authentication
*----------------------------------------------------------------
*/
gss_release_buffer(&lmin_s, &port->gss->outbuf); /*
} * Called when we have sent an authorization request for a password.
* Get the response and check it.
*/
static int
recv_and_check_password_packet(Port *port)
{
char *passwd;
int result;
if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED) passwd = recv_password_packet(port);
{
OM_uint32 lmin_s;
gss_delete_sec_context(&lmin_s, &port->gss->ctx, GSS_C_NO_BUFFER); if (passwd == NULL)
pg_GSS_error(ERROR, return STATUS_EOF; /* client wouldn't send password */
gettext_noop("accepting GSS security context failed"),
maj_stat, min_stat);
}
if (maj_stat == GSS_S_CONTINUE_NEEDED) result = md5_crypt_verify(port, port->user_name, passwd);
elog(DEBUG4, "GSS continue needed");
} while (maj_stat == GSS_S_CONTINUE_NEEDED); pfree(passwd);
if (port->gss->cred != GSS_C_NO_CREDENTIAL) return result;
{ }
/*
* Release service principal credentials
*/
gss_release_cred(&min_stat, &port->gss->cred);
}
/*
* GSS_S_COMPLETE indicates that authentication is now complete.
*
* Get the name of the user that authenticated, and compare it to the pg
* username that was specified for the connection.
*/
maj_stat = gss_display_name(&min_stat, port->gss->name, &gbuf, NULL);
if (maj_stat != GSS_S_COMPLETE)
pg_GSS_error(ERROR,
gettext_noop("retrieving GSS user name failed"),
maj_stat, min_stat);
/* /*----------------------------------------------------------------
* Split the username at the realm separator * MIT Kerberos authentication system - protocol version 5
*----------------------------------------------------------------
*/ */
if (strchr(gbuf.value, '@')) #ifdef KRB5
{
char *cp = strchr(gbuf.value, '@');
*cp = '\0'; static int
cp++; pg_krb5_init(void)
{
krb5_error_code retval;
char *khostname;
if (pg_krb_realm != NULL && strlen(pg_krb_realm)) if (pg_krb5_initialised)
{ return STATUS_OK;
/*
* Match the realm part of the name first
*/
if (pg_krb_caseins_users)
ret = pg_strcasecmp(pg_krb_realm, cp);
else
ret = strcmp(pg_krb_realm, cp);
if (ret) retval = krb5_init_context(&pg_krb5_context);
if (retval)
{ {
/* GSS realm does not match */ ereport(LOG,
elog(DEBUG2, (errmsg("Kerberos initialization returned error %d",
"GSSAPI realm (%s) and configured realm (%s) don't match", retval)));
cp, pg_krb_realm); com_err("postgres", retval, "while initializing krb5");
gss_release_buffer(&lmin_s, &gbuf);
return STATUS_ERROR; return STATUS_ERROR;
} }
}
}
else if (pg_krb_realm && strlen(pg_krb_realm))
{
elog(DEBUG2,
"GSSAPI did not return realm but realm matching was requested");
gss_release_buffer(&lmin_s, &gbuf); retval = krb5_kt_resolve(pg_krb5_context, pg_krb_server_keyfile, &pg_krb5_keytab);
if (retval)
{
ereport(LOG,
(errmsg("Kerberos keytab resolving returned error %d",
retval)));
com_err("postgres", retval, "while resolving keytab file \"%s\"",
pg_krb_server_keyfile);
krb5_free_context(pg_krb5_context);
return STATUS_ERROR; return STATUS_ERROR;
} }
if (pg_krb_caseins_users) /*
ret = pg_strcasecmp(port->user_name, gbuf.value); * If no hostname was specified, pg_krb_server_hostname is already NULL.
else * If it's set to blank, force it to NULL.
ret = strcmp(port->user_name, gbuf.value); */
khostname = pg_krb_server_hostname;
if (khostname && khostname[0] == '\0')
khostname = NULL;
if (ret) retval = krb5_sname_to_principal(pg_krb5_context,
khostname,
pg_krb_srvnam,
KRB5_NT_SRV_HST,
&pg_krb5_server);
if (retval)
{ {
/* GSS name and PGUSER are not equivalent */ ereport(LOG,
elog(DEBUG2, (errmsg("Kerberos sname_to_principal(\"%s\", \"%s\") returned error %d",
"provided username (%s) and GSSAPI username (%s) don't match", khostname ? khostname : "server hostname", pg_krb_srvnam, retval)));
port->user_name, (char *) gbuf.value); com_err("postgres", retval,
"while getting server principal for server \"%s\" for service \"%s\"",
gss_release_buffer(&lmin_s, &gbuf); khostname ? khostname : "server hostname", pg_krb_srvnam);
krb5_kt_close(pg_krb5_context, pg_krb5_keytab);
krb5_free_context(pg_krb5_context);
return STATUS_ERROR; return STATUS_ERROR;
} }
gss_release_buffer(&lmin_s, &gbuf); pg_krb5_initialised = 1;
return STATUS_OK; return STATUS_OK;
} }
#else /* no ENABLE_GSS */
/*
* pg_krb5_recvauth -- server routine to receive authentication information
* from the client
*
* We still need to compare the username obtained from the client's setup
* packet to the authenticated name.
*
* We have our own keytab file because postgres is unlikely to run as root,
* and so cannot read the default keytab.
*/
static int static int
pg_GSS_recvauth(Port *port) pg_krb5_recvauth(Port *port)
{
krb5_error_code retval;
int ret;
krb5_auth_context auth_context = NULL;
krb5_ticket *ticket;
char *kusername;
char *cp;
if (get_role_line(port->user_name) == NULL)
return STATUS_ERROR;
ret = pg_krb5_init();
if (ret != STATUS_OK)
return ret;
retval = krb5_recvauth(pg_krb5_context, &auth_context,
(krb5_pointer) & port->sock, pg_krb_srvnam,
pg_krb5_server, 0, pg_krb5_keytab, &ticket);
if (retval)
{
ereport(LOG,
(errmsg("Kerberos recvauth returned error %d",
retval)));
com_err("postgres", retval, "from krb5_recvauth");
return STATUS_ERROR;
}
/*
* The "client" structure comes out of the ticket and is therefore
* authenticated. Use it to check the username obtained from the
* postmaster startup packet.
*/
#if defined(HAVE_KRB5_TICKET_ENC_PART2)
retval = krb5_unparse_name(pg_krb5_context,
ticket->enc_part2->client, &kusername);
#elif defined(HAVE_KRB5_TICKET_CLIENT)
retval = krb5_unparse_name(pg_krb5_context,
ticket->client, &kusername);
#else
#error "bogus configuration"
#endif
if (retval)
{
ereport(LOG,
(errmsg("Kerberos unparse_name returned error %d",
retval)));
com_err("postgres", retval, "while unparsing client name");
krb5_free_ticket(pg_krb5_context, ticket);
krb5_auth_con_free(pg_krb5_context, auth_context);
return STATUS_ERROR;
}
cp = strchr(kusername, '@');
if (cp)
{
*cp = '\0';
cp++;
if (pg_krb_realm != NULL && strlen(pg_krb_realm))
{
/* Match realm against configured */
if (pg_krb_caseins_users)
ret = pg_strcasecmp(pg_krb_realm, cp);
else
ret = strcmp(pg_krb_realm, cp);
if (ret)
{
elog(DEBUG2,
"krb5 realm (%s) and configured realm (%s) don't match",
cp, pg_krb_realm);
krb5_free_ticket(pg_krb5_context, ticket);
krb5_auth_con_free(pg_krb5_context, auth_context);
return STATUS_ERROR;
}
}
}
else if (pg_krb_realm && strlen(pg_krb_realm))
{
elog(DEBUG2,
"krb5 did not return realm but realm matching was requested");
krb5_free_ticket(pg_krb5_context, ticket);
krb5_auth_con_free(pg_krb5_context, auth_context);
return STATUS_ERROR;
}
if (pg_krb_caseins_users)
ret = pg_strncasecmp(port->user_name, kusername, SM_DATABASE_USER);
else
ret = strncmp(port->user_name, kusername, SM_DATABASE_USER);
if (ret)
{
ereport(LOG,
(errmsg("unexpected Kerberos user name received from client (received \"%s\", expected \"%s\")",
port->user_name, kusername)));
ret = STATUS_ERROR;
}
else
ret = STATUS_OK;
krb5_free_ticket(pg_krb5_context, ticket);
krb5_auth_con_free(pg_krb5_context, auth_context);
free(kusername);
return ret;
}
#else
static int
pg_krb5_recvauth(Port *port)
{ {
ereport(LOG, ereport(LOG,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("GSSAPI not implemented on this server"))); errmsg("Kerberos 5 not implemented on this server")));
return STATUS_ERROR; return STATUS_ERROR;
} }
#endif /* KRB5 */
#endif /* ENABLE_GSS */
/*---------------------------------------------------------------- /*----------------------------------------------------------------
* SSPI authentication system * GSSAPI authentication system
*---------------------------------------------------------------- *----------------------------------------------------------------
*/ */
#ifdef ENABLE_GSS
#ifdef ENABLE_SSPI #if defined(WIN32) && !defined(WIN32_ONLY_COMPILER)
/*
* MIT Kerberos GSSAPI DLL doesn't properly export the symbols for MingW
* that contain the OIDs required. Redefine here, values copied
* from src/athena/auth/krb5/src/lib/gssapi/generic/gssapi_generic.c
*/
static const gss_OID_desc GSS_C_NT_USER_NAME_desc =
{10, (void *) "\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x02"};
static GSS_DLLIMP gss_OID GSS_C_NT_USER_NAME = &GSS_C_NT_USER_NAME_desc;
#endif
typedef SECURITY_STATUS
(WINAPI * QUERY_SECURITY_CONTEXT_TOKEN_FN) (
PCtxtHandle, void **);
static void static void
pg_SSPI_error(int severity, char *errmsg, SECURITY_STATUS r) pg_GSS_error(int severity, char *errmsg, OM_uint32 maj_stat, OM_uint32 min_stat)
{ {
char sysmsg[256]; gss_buffer_desc gmsg;
OM_uint32 lmaj_s,
lmin_s,
msg_ctx;
char msg_major[128],
msg_minor[128];
if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, r, 0, sysmsg, sizeof(sysmsg), NULL) == 0) /* Fetch major status message */
ereport(severity, msg_ctx = 0;
(errmsg_internal("%s", errmsg), lmaj_s = gss_display_status(&lmin_s, maj_stat, GSS_C_GSS_CODE,
errdetail("SSPI error %x", (unsigned int) r))); GSS_C_NO_OID, &msg_ctx, &gmsg);
else strlcpy(msg_major, gmsg.value, sizeof(msg_major));
gss_release_buffer(&lmin_s, &gmsg);
if (msg_ctx)
/*
* More than one message available. XXX: Should we loop and read all
* messages? (same below)
*/
ereport(WARNING,
(errmsg_internal("incomplete GSS error report")));
/* Fetch mechanism minor status message */
msg_ctx = 0;
lmaj_s = gss_display_status(&lmin_s, min_stat, GSS_C_MECH_CODE,
GSS_C_NO_OID, &msg_ctx, &gmsg);
strlcpy(msg_minor, gmsg.value, sizeof(msg_minor));
gss_release_buffer(&lmin_s, &gmsg);
if (msg_ctx)
ereport(WARNING,
(errmsg_internal("incomplete GSS minor error report")));
/*
* errmsg_internal, since translation of the first part must be done
* before calling this function anyway.
*/
ereport(severity, ereport(severity,
(errmsg_internal("%s", errmsg), (errmsg_internal("%s", errmsg),
errdetail("%s (%x)", sysmsg, (unsigned int) r))); errdetail("%s: %s", msg_major, msg_minor)));
} }
static int static int
pg_SSPI_recvauth(Port *port) pg_GSS_recvauth(Port *port)
{ {
OM_uint32 maj_stat,
min_stat,
lmin_s,
gflags;
int mtype; int mtype;
int ret;
StringInfoData buf; StringInfoData buf;
SECURITY_STATUS r; gss_buffer_desc gbuf;
CredHandle sspicred;
CtxtHandle *sspictx = NULL,
newctx;
TimeStamp expiry;
ULONG contextattr;
SecBufferDesc inbuf;
SecBufferDesc outbuf;
SecBuffer OutBuffers[1];
SecBuffer InBuffers[1];
HANDLE token;
TOKEN_USER *tokenuser;
DWORD retlen;
char accountname[MAXPGPATH];
char domainname[MAXPGPATH];
DWORD accountnamesize = sizeof(accountname);
DWORD domainnamesize = sizeof(domainname);
SID_NAME_USE accountnameuse;
HMODULE secur32;
QUERY_SECURITY_CONTEXT_TOKEN_FN _QuerySecurityContextToken;
/* /*
* SSPI auth is not supported for protocol versions before 3, because it * GSS auth is not supported for protocol versions before 3, because it
* relies on the overall message length word to determine the SSPI payload * relies on the overall message length word to determine the GSS payload
* size in AuthenticationGSSContinue and PasswordMessage messages. * size in AuthenticationGSSContinue and PasswordMessage messages.
* (This is, in fact, a design error in our SSPI support, because protocol * (This is, in fact, a design error in our GSS support, because protocol
* messages are supposed to be parsable without relying on the length * messages are supposed to be parsable without relying on the length
* word; but it's not worth changing it now.) * word; but it's not worth changing it now.)
*/ */
if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3) if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
ereport(FATAL, ereport(FATAL,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("SSPI is not supported in protocol version 2"))); errmsg("GSSAPI is not supported in protocol version 2")));
if (pg_krb_server_keyfile && strlen(pg_krb_server_keyfile) > 0)
{
/* /*
* Acquire a handle to the server credentials. * Set default Kerberos keytab file for the Krb5 mechanism.
*
* setenv("KRB5_KTNAME", pg_krb_server_keyfile, 0); except setenv()
* not always available.
*/ */
r = AcquireCredentialsHandle(NULL, if (getenv("KRB5_KTNAME") == NULL)
"negotiate", {
SECPKG_CRED_INBOUND, size_t kt_len = strlen(pg_krb_server_keyfile) + 14;
NULL, char *kt_path = malloc(kt_len);
NULL,
NULL, if (!kt_path)
NULL, {
&sspicred, ereport(LOG,
&expiry); (errcode(ERRCODE_OUT_OF_MEMORY),
if (r != SEC_E_OK) errmsg("out of memory")));
pg_SSPI_error(ERROR, return STATUS_ERROR;
gettext_noop("could not acquire SSPI credentials handle"), r); }
snprintf(kt_path, kt_len, "KRB5_KTNAME=%s", pg_krb_server_keyfile);
putenv(kt_path);
}
}
/* /*
* Loop through SSPI message exchange. This exchange can consist of * We accept any service principal that's present in our keytab. This
* increases interoperability between kerberos implementations that see
* for example case sensitivity differently, while not really opening up
* any vector of attack.
*/
port->gss->cred = GSS_C_NO_CREDENTIAL;
/*
* Initialize sequence with an empty context
*/
port->gss->ctx = GSS_C_NO_CONTEXT;
/*
* Loop through GSSAPI message exchange. This exchange can consist of
* multiple messags sent in both directions. First message is always from * multiple messags sent in both directions. First message is always from
* the client. All messages from client to server are password packets * the client. All messages from client to server are password packets
* (type 'p'). * (type 'p').
...@@ -725,12 +888,12 @@ pg_SSPI_recvauth(Port *port) ...@@ -725,12 +888,12 @@ pg_SSPI_recvauth(Port *port)
if (mtype != EOF) if (mtype != EOF)
ereport(COMMERROR, ereport(COMMERROR,
(errcode(ERRCODE_PROTOCOL_VIOLATION), (errcode(ERRCODE_PROTOCOL_VIOLATION),
errmsg("expected SSPI response, got message type %d", errmsg("expected GSS response, got message type %d",
mtype))); mtype)));
return STATUS_ERROR; return STATUS_ERROR;
} }
/* Get the actual SSPI token */ /* Get the actual GSS token */
initStringInfo(&buf); initStringInfo(&buf);
if (pq_getmessage(&buf, 2000)) if (pq_getmessage(&buf, 2000))
{ {
...@@ -739,468 +902,460 @@ pg_SSPI_recvauth(Port *port) ...@@ -739,468 +902,460 @@ pg_SSPI_recvauth(Port *port)
return STATUS_ERROR; return STATUS_ERROR;
} }
/* Map to SSPI style buffer */ /* Map to GSSAPI style buffer */
inbuf.ulVersion = SECBUFFER_VERSION; gbuf.length = buf.len;
inbuf.cBuffers = 1; gbuf.value = buf.data;
inbuf.pBuffers = InBuffers;
InBuffers[0].pvBuffer = buf.data;
InBuffers[0].cbBuffer = buf.len;
InBuffers[0].BufferType = SECBUFFER_TOKEN;
/* Prepare output buffer */
OutBuffers[0].pvBuffer = NULL;
OutBuffers[0].BufferType = SECBUFFER_TOKEN;
OutBuffers[0].cbBuffer = 0;
outbuf.cBuffers = 1;
outbuf.pBuffers = OutBuffers;
outbuf.ulVersion = SECBUFFER_VERSION;
elog(DEBUG4, "Processing received SSPI token of length %u", elog(DEBUG4, "Processing received GSS token of length %u",
(unsigned int) buf.len); (unsigned int) gbuf.length);
r = AcceptSecurityContext(&sspicred, maj_stat = gss_accept_sec_context(
sspictx, &min_stat,
&inbuf, &port->gss->ctx,
ASC_REQ_ALLOCATE_MEMORY, port->gss->cred,
SECURITY_NETWORK_DREP, &gbuf,
&newctx, GSS_C_NO_CHANNEL_BINDINGS,
&outbuf, &port->gss->name,
&contextattr, NULL,
&port->gss->outbuf,
&gflags,
NULL,
NULL); NULL);
/* input buffer no longer used */ /* gbuf no longer used */
pfree(buf.data); pfree(buf.data);
if (outbuf.cBuffers > 0 && outbuf.pBuffers[0].cbBuffer > 0) elog(DEBUG5, "gss_accept_sec_context major: %d, "
"minor: %d, outlen: %u, outflags: %x",
maj_stat, min_stat,
(unsigned int) port->gss->outbuf.length, gflags);
if (port->gss->outbuf.length != 0)
{ {
/* /*
* Negotiation generated data to be sent to the client. * Negotiation generated data to be sent to the client.
*/ */
elog(DEBUG4, "sending SSPI response token of length %u", OM_uint32 lmin_s;
(unsigned int) outbuf.pBuffers[0].cbBuffer);
port->gss->outbuf.length = outbuf.pBuffers[0].cbBuffer; elog(DEBUG4, "sending GSS response token of length %u",
port->gss->outbuf.value = outbuf.pBuffers[0].pvBuffer; (unsigned int) port->gss->outbuf.length);
sendAuthRequest(port, AUTH_REQ_GSS_CONT); sendAuthRequest(port, AUTH_REQ_GSS_CONT);
FreeContextBuffer(outbuf.pBuffers[0].pvBuffer); gss_release_buffer(&lmin_s, &port->gss->outbuf);
}
if (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)
{
if (sspictx != NULL)
{
DeleteSecurityContext(sspictx);
free(sspictx);
}
FreeCredentialsHandle(&sspicred);
pg_SSPI_error(ERROR,
gettext_noop("could not accept SSPI security context"), r);
} }
if (sspictx == NULL) if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
{ {
sspictx = malloc(sizeof(CtxtHandle)); OM_uint32 lmin_s;
if (sspictx == NULL)
ereport(ERROR,
(errmsg("out of memory")));
memcpy(sspictx, &newctx, sizeof(CtxtHandle)); gss_delete_sec_context(&lmin_s, &port->gss->ctx, GSS_C_NO_BUFFER);
pg_GSS_error(ERROR,
gettext_noop("accepting GSS security context failed"),
maj_stat, min_stat);
} }
if (r == SEC_I_CONTINUE_NEEDED) if (maj_stat == GSS_S_CONTINUE_NEEDED)
elog(DEBUG4, "SSPI continue needed"); elog(DEBUG4, "GSS continue needed");
} while (r == SEC_I_CONTINUE_NEEDED);
} while (maj_stat == GSS_S_CONTINUE_NEEDED);
if (port->gss->cred != GSS_C_NO_CREDENTIAL)
{
/* /*
* Release service principal credentials * Release service principal credentials
*/ */
FreeCredentialsHandle(&sspicred); gss_release_cred(&min_stat, &port->gss->cred);
}
/* /*
* SEC_E_OK indicates that authentication is now complete. * GSS_S_COMPLETE indicates that authentication is now complete.
* *
* Get the name of the user that authenticated, and compare it to the pg * Get the name of the user that authenticated, and compare it to the pg
* username that was specified for the connection. * username that was specified for the connection.
*
* MingW is missing the export for QuerySecurityContextToken in the
* secur32 library, so we have to load it dynamically.
*/ */
maj_stat = gss_display_name(&min_stat, port->gss->name, &gbuf, NULL);
secur32 = LoadLibrary("SECUR32.DLL"); if (maj_stat != GSS_S_COMPLETE)
if (secur32 == NULL) pg_GSS_error(ERROR,
ereport(ERROR, gettext_noop("retrieving GSS user name failed"),
(errmsg_internal("could not load secur32.dll: %d", maj_stat, min_stat);
(int) GetLastError())));
_QuerySecurityContextToken = (QUERY_SECURITY_CONTEXT_TOKEN_FN)
GetProcAddress(secur32, "QuerySecurityContextToken");
if (_QuerySecurityContextToken == NULL)
{
FreeLibrary(secur32);
ereport(ERROR,
(errmsg_internal("could not locate QuerySecurityContextToken in secur32.dll: %d",
(int) GetLastError())));
}
r = (_QuerySecurityContextToken) (sspictx, &token);
if (r != SEC_E_OK)
{
FreeLibrary(secur32);
pg_SSPI_error(ERROR,
gettext_noop("could not get security token from context"), r);
}
FreeLibrary(secur32);
/* /*
* No longer need the security context, everything from here on uses the * Split the username at the realm separator
* token instead.
*/ */
DeleteSecurityContext(sspictx); if (strchr(gbuf.value, '@'))
free(sspictx); {
char *cp = strchr(gbuf.value, '@');
if (!GetTokenInformation(token, TokenUser, NULL, 0, &retlen) && GetLastError() != 122)
ereport(ERROR,
(errmsg_internal("could not get token user size: error code %d",
(int) GetLastError())));
tokenuser = malloc(retlen);
if (tokenuser == NULL)
ereport(ERROR,
(errmsg("out of memory")));
if (!GetTokenInformation(token, TokenUser, tokenuser, retlen, &retlen))
ereport(ERROR,
(errmsg_internal("could not get user token: error code %d",
(int) GetLastError())));
if (!LookupAccountSid(NULL, tokenuser->User.Sid, accountname, &accountnamesize,
domainname, &domainnamesize, &accountnameuse))
ereport(ERROR,
(errmsg_internal("could not lookup acconut sid: error code %d",
(int) GetLastError())));
free(tokenuser); *cp = '\0';
cp++;
if (pg_krb_realm != NULL && strlen(pg_krb_realm))
{
/* /*
* Compare realm/domain if requested. In SSPI, always compare case * Match the realm part of the name first
* insensitive.
*/ */
if (pg_krb_realm && strlen(pg_krb_realm)) if (pg_krb_caseins_users)
ret = pg_strcasecmp(pg_krb_realm, cp);
else
ret = strcmp(pg_krb_realm, cp);
if (ret)
{ {
if (pg_strcasecmp(pg_krb_realm, domainname)) /* GSS realm does not match */
elog(DEBUG2,
"GSSAPI realm (%s) and configured realm (%s) don't match",
cp, pg_krb_realm);
gss_release_buffer(&lmin_s, &gbuf);
return STATUS_ERROR;
}
}
}
else if (pg_krb_realm && strlen(pg_krb_realm))
{ {
elog(DEBUG2, elog(DEBUG2,
"SSPI domain (%s) and configured domain (%s) don't match", "GSSAPI did not return realm but realm matching was requested");
domainname, pg_krb_realm);
gss_release_buffer(&lmin_s, &gbuf);
return STATUS_ERROR; return STATUS_ERROR;
} }
}
/* if (pg_krb_caseins_users)
* We have the username (without domain/realm) in accountname, compare to ret = pg_strcasecmp(port->user_name, gbuf.value);
* the supplied value. In SSPI, always compare case insensitive. else
*/ ret = strcmp(port->user_name, gbuf.value);
if (pg_strcasecmp(port->user_name, accountname))
if (ret)
{ {
/* GSS name and PGUSER are not equivalent */ /* GSS name and PGUSER are not equivalent */
elog(DEBUG2, elog(DEBUG2,
"provided username (%s) and SSPI username (%s) don't match", "provided username (%s) and GSSAPI username (%s) don't match",
port->user_name, accountname); port->user_name, (char *) gbuf.value);
gss_release_buffer(&lmin_s, &gbuf);
return STATUS_ERROR; return STATUS_ERROR;
} }
gss_release_buffer(&lmin_s, &gbuf);
return STATUS_OK; return STATUS_OK;
} }
#else /* no ENABLE_SSPI */ #else /* no ENABLE_GSS */
static int static int
pg_SSPI_recvauth(Port *port) pg_GSS_recvauth(Port *port)
{ {
ereport(LOG, ereport(LOG,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("SSPI not implemented on this server"))); errmsg("GSSAPI not implemented on this server")));
return STATUS_ERROR; return STATUS_ERROR;
} }
#endif /* ENABLE_SSPI */ #endif /* ENABLE_GSS */
/* /*----------------------------------------------------------------
* Tell the user the authentication failed, but not (much about) why. * SSPI authentication system
* *----------------------------------------------------------------
* There is a tradeoff here between security concerns and making life
* unnecessarily difficult for legitimate users. We would not, for example,
* want to report the password we were expecting to receive...
* But it seems useful to report the username and authorization method
* in use, and these are items that must be presumed known to an attacker
* anyway.
* Note that many sorts of failure report additional information in the
* postmaster log, which we hope is only readable by good guys.
*/ */
#ifdef ENABLE_SSPI
static void static void
auth_failed(Port *port, int status) pg_SSPI_error(int severity, char *errmsg, SECURITY_STATUS r)
{ {
const char *errstr; char sysmsg[256];
/*
* If we failed due to EOF from client, just quit; there's no point in
* trying to send a message to the client, and not much point in logging
* the failure in the postmaster log. (Logging the failure might be
* desirable, were it not for the fact that libpq closes the connection
* unceremoniously if challenged for a password when it hasn't got one to
* send. We'll get a useless log entry for every psql connection under
* password auth, even if it's perfectly successful, if we log STATUS_EOF
* events.)
*/
if (status == STATUS_EOF)
proc_exit(0);
switch (port->auth_method)
{
case uaReject:
errstr = gettext_noop("authentication failed for user \"%s\": host rejected");
break;
case uaKrb5:
errstr = gettext_noop("Kerberos 5 authentication failed for user \"%s\"");
break;
case uaGSS:
errstr = gettext_noop("GSSAPI authentication failed for user \"%s\"");
break;
case uaSSPI:
errstr = gettext_noop("SSPI authentication failed for user \"%s\"");
break;
case uaTrust:
errstr = gettext_noop("\"trust\" authentication failed for user \"%s\"");
break;
case uaIdent:
errstr = gettext_noop("Ident authentication failed for user \"%s\"");
break;
case uaMD5:
case uaCrypt:
case uaPassword:
errstr = gettext_noop("password authentication failed for user \"%s\"");
break;
#ifdef USE_PAM
case uaPAM:
errstr = gettext_noop("PAM authentication failed for user \"%s\"");
break;
#endif /* USE_PAM */
#ifdef USE_LDAP
case uaLDAP:
errstr = gettext_noop("LDAP authentication failed for user \"%s\"");
break;
#endif /* USE_LDAP */
default:
errstr = gettext_noop("authentication failed for user \"%s\": invalid authentication method");
break;
}
ereport(FATAL, if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, r, 0, sysmsg, sizeof(sysmsg), NULL) == 0)
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION), ereport(severity,
errmsg(errstr, port->user_name))); (errmsg_internal("%s", errmsg),
/* doesn't return */ errdetail("SSPI error %x", (unsigned int) r)));
else
ereport(severity,
(errmsg_internal("%s", errmsg),
errdetail("%s (%x)", sysmsg, (unsigned int) r)));
} }
static int
/* pg_SSPI_recvauth(Port *port)
* Client authentication starts here. If there is an error, this
* function does not return and the backend process is terminated.
*/
void
ClientAuthentication(Port *port)
{ {
int status = STATUS_ERROR; int mtype;
StringInfoData buf;
SECURITY_STATUS r;
CredHandle sspicred;
CtxtHandle *sspictx = NULL,
newctx;
TimeStamp expiry;
ULONG contextattr;
SecBufferDesc inbuf;
SecBufferDesc outbuf;
SecBuffer OutBuffers[1];
SecBuffer InBuffers[1];
HANDLE token;
TOKEN_USER *tokenuser;
DWORD retlen;
char accountname[MAXPGPATH];
char domainname[MAXPGPATH];
DWORD accountnamesize = sizeof(accountname);
DWORD domainnamesize = sizeof(domainname);
SID_NAME_USE accountnameuse;
HMODULE secur32;
QUERY_SECURITY_CONTEXT_TOKEN_FN _QuerySecurityContextToken;
/* /*
* Get the authentication method to use for this frontend/database * SSPI auth is not supported for protocol versions before 3, because it
* combination. Note: a failure return indicates a problem with the hba * relies on the overall message length word to determine the SSPI payload
* config file, not with the request. hba.c should have dropped an error * size in AuthenticationGSSContinue and PasswordMessage messages.
* message into the postmaster logfile if it failed. * (This is, in fact, a design error in our SSPI support, because protocol
* messages are supposed to be parsable without relying on the length
* word; but it's not worth changing it now.)
*/ */
if (hba_getauthmethod(port) != STATUS_OK) if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
ereport(FATAL, ereport(FATAL,
(errcode(ERRCODE_CONFIG_FILE_ERROR), (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("missing or erroneous pg_hba.conf file"), errmsg("SSPI is not supported in protocol version 2")));
errhint("See server log for details.")));
switch (port->auth_method) /*
{ * Acquire a handle to the server credentials.
case uaReject: */
r = AcquireCredentialsHandle(NULL,
"negotiate",
SECPKG_CRED_INBOUND,
NULL,
NULL,
NULL,
NULL,
&sspicred,
&expiry);
if (r != SEC_E_OK)
pg_SSPI_error(ERROR,
gettext_noop("could not acquire SSPI credentials handle"), r);
/* /*
* This could have come from an explicit "reject" entry in * Loop through SSPI message exchange. This exchange can consist of
* pg_hba.conf, but more likely it means there was no matching * multiple messags sent in both directions. First message is always from
* entry. Take pity on the poor user and issue a helpful error * the client. All messages from client to server are password packets
* message. NOTE: this is not a security breach, because all the * (type 'p').
* info reported here is known at the frontend and must be assumed
* known to bad guys. We're merely helping out the less clueful
* good guys.
*/ */
do
{ {
char hostinfo[NI_MAXHOST]; mtype = pq_getbyte();
if (mtype != 'p')
pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen, {
hostinfo, sizeof(hostinfo), /* Only log error if client didn't disconnect. */
NULL, 0, if (mtype != EOF)
NI_NUMERICHOST); ereport(COMMERROR,
(errcode(ERRCODE_PROTOCOL_VIOLATION),
errmsg("expected SSPI response, got message type %d",
mtype)));
return STATUS_ERROR;
}
#ifdef USE_SSL /* Get the actual SSPI token */
ereport(FATAL, initStringInfo(&buf);
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION), if (pq_getmessage(&buf, 2000))
errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\", %s", {
hostinfo, port->user_name, port->database_name, /* EOF - pq_getmessage already logged error */
port->ssl ? _("SSL on") : _("SSL off")))); pfree(buf.data);
#else return STATUS_ERROR;
ereport(FATAL,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\"",
hostinfo, port->user_name, port->database_name)));
#endif
break;
} }
case uaKrb5: /* Map to SSPI style buffer */
sendAuthRequest(port, AUTH_REQ_KRB5); inbuf.ulVersion = SECBUFFER_VERSION;
status = pg_krb5_recvauth(port); inbuf.cBuffers = 1;
break; inbuf.pBuffers = InBuffers;
InBuffers[0].pvBuffer = buf.data;
InBuffers[0].cbBuffer = buf.len;
InBuffers[0].BufferType = SECBUFFER_TOKEN;
case uaGSS: /* Prepare output buffer */
sendAuthRequest(port, AUTH_REQ_GSS); OutBuffers[0].pvBuffer = NULL;
status = pg_GSS_recvauth(port); OutBuffers[0].BufferType = SECBUFFER_TOKEN;
break; OutBuffers[0].cbBuffer = 0;
outbuf.cBuffers = 1;
outbuf.pBuffers = OutBuffers;
outbuf.ulVersion = SECBUFFER_VERSION;
case uaSSPI:
sendAuthRequest(port, AUTH_REQ_SSPI);
status = pg_SSPI_recvauth(port);
break;
case uaIdent: elog(DEBUG4, "Processing received SSPI token of length %u",
(unsigned int) buf.len);
r = AcceptSecurityContext(&sspicred,
sspictx,
&inbuf,
ASC_REQ_ALLOCATE_MEMORY,
SECURITY_NETWORK_DREP,
&newctx,
&outbuf,
&contextattr,
NULL);
/* input buffer no longer used */
pfree(buf.data);
if (outbuf.cBuffers > 0 && outbuf.pBuffers[0].cbBuffer > 0)
{
/* /*
* If we are doing ident on unix-domain sockets, use SCM_CREDS * Negotiation generated data to be sent to the client.
* only if it is defined and SO_PEERCRED isn't.
*/ */
#if !defined(HAVE_GETPEEREID) && !defined(SO_PEERCRED) && \ elog(DEBUG4, "sending SSPI response token of length %u",
(defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || \ (unsigned int) outbuf.pBuffers[0].cbBuffer);
(defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS)))
if (port->raddr.addr.ss_family == AF_UNIX) port->gss->outbuf.length = outbuf.pBuffers[0].cbBuffer;
port->gss->outbuf.value = outbuf.pBuffers[0].pvBuffer;
sendAuthRequest(port, AUTH_REQ_GSS_CONT);
FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
}
if (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)
{ {
#if defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED) if (sspictx != NULL)
{
DeleteSecurityContext(sspictx);
free(sspictx);
}
FreeCredentialsHandle(&sspicred);
pg_SSPI_error(ERROR,
gettext_noop("could not accept SSPI security context"), r);
}
/* if (sspictx == NULL)
* Receive credentials on next message receipt, BSD/OS, {
* NetBSD. We need to set this before the client sends the sspictx = malloc(sizeof(CtxtHandle));
* next packet. if (sspictx == NULL)
*/ ereport(ERROR,
int on = 1; (errmsg("out of memory")));
if (setsockopt(port->sock, 0, LOCAL_CREDS, &on, sizeof(on)) < 0) memcpy(sspictx, &newctx, sizeof(CtxtHandle));
ereport(FATAL, }
(errcode_for_socket_access(),
errmsg("could not enable credential reception: %m"))); if (r == SEC_I_CONTINUE_NEEDED)
#endif elog(DEBUG4, "SSPI continue needed");
sendAuthRequest(port, AUTH_REQ_SCM_CREDS); } while (r == SEC_I_CONTINUE_NEEDED);
}
#endif
status = authident(port);
break;
case uaMD5:
sendAuthRequest(port, AUTH_REQ_MD5);
status = recv_and_check_password_packet(port);
break;
case uaCrypt: /*
sendAuthRequest(port, AUTH_REQ_CRYPT); * Release service principal credentials
status = recv_and_check_password_packet(port); */
break; FreeCredentialsHandle(&sspicred);
case uaPassword:
sendAuthRequest(port, AUTH_REQ_PASSWORD);
status = recv_and_check_password_packet(port);
break;
#ifdef USE_PAM /*
case uaPAM: * SEC_E_OK indicates that authentication is now complete.
pam_port_cludge = port; *
status = CheckPAMAuth(port, port->user_name, ""); * Get the name of the user that authenticated, and compare it to the pg
break; * username that was specified for the connection.
#endif /* USE_PAM */ *
* MingW is missing the export for QuerySecurityContextToken in the
* secur32 library, so we have to load it dynamically.
*/
#ifdef USE_LDAP secur32 = LoadLibrary("SECUR32.DLL");
case uaLDAP: if (secur32 == NULL)
status = CheckLDAPAuth(port); ereport(ERROR,
break; (errmsg_internal("could not load secur32.dll: %d",
#endif (int) GetLastError())));
case uaTrust: _QuerySecurityContextToken = (QUERY_SECURITY_CONTEXT_TOKEN_FN)
status = STATUS_OK; GetProcAddress(secur32, "QuerySecurityContextToken");
break; if (_QuerySecurityContextToken == NULL)
{
FreeLibrary(secur32);
ereport(ERROR,
(errmsg_internal("could not locate QuerySecurityContextToken in secur32.dll: %d",
(int) GetLastError())));
} }
if (status == STATUS_OK) r = (_QuerySecurityContextToken) (sspictx, &token);
sendAuthRequest(port, AUTH_REQ_OK); if (r != SEC_E_OK)
else {
auth_failed(port, status); FreeLibrary(secur32);
} pg_SSPI_error(ERROR,
gettext_noop("could not get security token from context"), r);
}
FreeLibrary(secur32);
/* /*
* Send an authentication request packet to the frontend. * No longer need the security context, everything from here on uses the
* token instead.
*/ */
static void DeleteSecurityContext(sspictx);
sendAuthRequest(Port *port, AuthRequest areq) free(sspictx);
{
StringInfoData buf;
pq_beginmessage(&buf, 'R'); if (!GetTokenInformation(token, TokenUser, NULL, 0, &retlen) && GetLastError() != 122)
pq_sendint(&buf, (int32) areq, sizeof(int32)); ereport(ERROR,
(errmsg_internal("could not get token user size: error code %d",
(int) GetLastError())));
/* Add the salt for encrypted passwords. */ tokenuser = malloc(retlen);
if (areq == AUTH_REQ_MD5) if (tokenuser == NULL)
pq_sendbytes(&buf, port->md5Salt, 4); ereport(ERROR,
else if (areq == AUTH_REQ_CRYPT) (errmsg("out of memory")));
pq_sendbytes(&buf, port->cryptSalt, 2);
#if defined(ENABLE_GSS) || defined(ENABLE_SSPI) if (!GetTokenInformation(token, TokenUser, tokenuser, retlen, &retlen))
ereport(ERROR,
(errmsg_internal("could not get user token: error code %d",
(int) GetLastError())));
if (!LookupAccountSid(NULL, tokenuser->User.Sid, accountname, &accountnamesize,
domainname, &domainnamesize, &accountnameuse))
ereport(ERROR,
(errmsg_internal("could not lookup acconut sid: error code %d",
(int) GetLastError())));
free(tokenuser);
/* /*
* Add the authentication data for the next step of the GSSAPI or SSPI * Compare realm/domain if requested. In SSPI, always compare case
* negotiation. * insensitive.
*/ */
else if (areq == AUTH_REQ_GSS_CONT) if (pg_krb_realm && strlen(pg_krb_realm))
{ {
if (port->gss->outbuf.length > 0) if (pg_strcasecmp(pg_krb_realm, domainname))
{ {
elog(DEBUG4, "sending GSS token of length %u", elog(DEBUG2,
(unsigned int) port->gss->outbuf.length); "SSPI domain (%s) and configured domain (%s) don't match",
domainname, pg_krb_realm);
pq_sendbytes(&buf, port->gss->outbuf.value, port->gss->outbuf.length); return STATUS_ERROR;
} }
} }
#endif
pq_endmessage(&buf);
/* /*
* Flush message so client will see it, except for AUTH_REQ_OK, which need * We have the username (without domain/realm) in accountname, compare to
* not be sent until we are ready for queries. * the supplied value. In SSPI, always compare case insensitive.
*/ */
if (areq != AUTH_REQ_OK) if (pg_strcasecmp(port->user_name, accountname))
pq_flush(); {
/* GSS name and PGUSER are not equivalent */
elog(DEBUG2,
"provided username (%s) and SSPI username (%s) don't match",
port->user_name, accountname);
return STATUS_ERROR;
}
return STATUS_OK;
}
#else /* no ENABLE_SSPI */
static int
pg_SSPI_recvauth(Port *port)
{
ereport(LOG,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("SSPI not implemented on this server")));
return STATUS_ERROR;
} }
#endif /* ENABLE_SSPI */
/*---------------------------------------------------------------- /*----------------------------------------------------------------
* Ident authentication system * Ident authentication system
*---------------------------------------------------------------- *----------------------------------------------------------------
...@@ -1655,7 +1810,6 @@ authident(hbaPort *port) ...@@ -1655,7 +1810,6 @@ authident(hbaPort *port)
* PAM authentication system * PAM authentication system
*---------------------------------------------------------------- *----------------------------------------------------------------
*/ */
#ifdef USE_PAM #ifdef USE_PAM
/* /*
...@@ -1835,6 +1989,11 @@ CheckPAMAuth(Port *port, char *user, char *password) ...@@ -1835,6 +1989,11 @@ CheckPAMAuth(Port *port, char *user, char *password)
#endif /* USE_PAM */ #endif /* USE_PAM */
/*----------------------------------------------------------------
* LDAP authentication system
*----------------------------------------------------------------
*/
#ifdef USE_LDAP #ifdef USE_LDAP
static int static int
...@@ -2014,94 +2173,3 @@ CheckLDAPAuth(Port *port) ...@@ -2014,94 +2173,3 @@ CheckLDAPAuth(Port *port)
} }
#endif /* USE_LDAP */ #endif /* USE_LDAP */
/*
* Collect password response packet from frontend.
*
* Returns NULL if couldn't get password, else palloc'd string.
*/
static char *
recv_password_packet(Port *port)
{
StringInfoData buf;
if (PG_PROTOCOL_MAJOR(port->proto) >= 3)
{
/* Expect 'p' message type */
int mtype;
mtype = pq_getbyte();
if (mtype != 'p')
{
/*
* If the client just disconnects without offering a password,
* don't make a log entry. This is legal per protocol spec and in
* fact commonly done by psql, so complaining just clutters the
* log.
*/
if (mtype != EOF)
ereport(COMMERROR,
(errcode(ERRCODE_PROTOCOL_VIOLATION),
errmsg("expected password response, got message type %d",
mtype)));
return NULL; /* EOF or bad message type */
}
}
else
{
/* For pre-3.0 clients, avoid log entry if they just disconnect */
if (pq_peekbyte() == EOF)
return NULL; /* EOF */
}
initStringInfo(&buf);
if (pq_getmessage(&buf, 1000)) /* receive password */
{
/* EOF - pq_getmessage already logged a suitable message */
pfree(buf.data);
return NULL;
}
/*
* Apply sanity check: password packet length should agree with length of
* contained string. Note it is safe to use strlen here because
* StringInfo is guaranteed to have an appended '\0'.
*/
if (strlen(buf.data) + 1 != buf.len)
ereport(COMMERROR,
(errcode(ERRCODE_PROTOCOL_VIOLATION),
errmsg("invalid password packet size")));
/* Do not echo password to logs, for security. */
ereport(DEBUG5,
(errmsg("received password packet")));
/*
* Return the received string. Note we do not attempt to do any
* character-set conversion on it; since we don't yet know the client's
* encoding, there wouldn't be much point.
*/
return buf.data;
}
/*
* Called when we have sent an authorization request for a password.
* Get the response and check it.
*/
static int
recv_and_check_password_packet(Port *port)
{
char *passwd;
int result;
passwd = recv_password_packet(port);
if (passwd == NULL)
return STATUS_EOF; /* client wouldn't send password */
result = md5_crypt_verify(port, port->user_name, passwd);
pfree(passwd);
return result;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment