/src/backend/libpq/auth.c
C | 3410 lines | 2225 code | 438 blank | 747 comment | 446 complexity | b6304eb2745dce163c35f3e3c8f345d7 MD5 | raw file
Possible License(s): AGPL-3.0
Large files files are truncated, but you can click here to view the full file
- /*-------------------------------------------------------------------------
- *
- * auth.c
- * Routines to handle network authentication
- *
- * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
- * Portions Copyright (c) 1994, Regents of the University of California
- *
- *
- * IDENTIFICATION
- * src/backend/libpq/auth.c
- *
- *-------------------------------------------------------------------------
- */
- #include "postgres.h"
- #include <sys/param.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <unistd.h>
- #ifdef HAVE_SYS_SELECT_H
- #include <sys/select.h>
- #endif
- #include "commands/user.h"
- #include "common/ip.h"
- #include "common/md5.h"
- #include "common/scram-common.h"
- #include "libpq/auth.h"
- #include "libpq/crypt.h"
- #include "libpq/libpq.h"
- #include "libpq/pqformat.h"
- #include "libpq/scram.h"
- #include "miscadmin.h"
- #include "port/pg_bswap.h"
- #include "replication/walsender.h"
- #include "storage/ipc.h"
- #include "utils/memutils.h"
- #include "utils/timestamp.h"
- /*----------------------------------------------------------------
- * Global authentication functions
- *----------------------------------------------------------------
- */
- static void sendAuthRequest(Port *port, AuthRequest areq, const char *extradata,
- int extralen);
- static void auth_failed(Port *port, int status, char *logdetail);
- static char *recv_password_packet(Port *port);
- /*----------------------------------------------------------------
- * Password-based authentication methods (password, md5, and scram-sha-256)
- *----------------------------------------------------------------
- */
- static int CheckPasswordAuth(Port *port, char **logdetail);
- static int CheckPWChallengeAuth(Port *port, char **logdetail);
- static int CheckMD5Auth(Port *port, char *shadow_pass, char **logdetail);
- static int CheckSCRAMAuth(Port *port, char *shadow_pass, char **logdetail);
- /*----------------------------------------------------------------
- * Ident authentication
- *----------------------------------------------------------------
- */
- /* Max size of username ident server can return (per RFC 1413) */
- #define IDENT_USERNAME_MAX 512
- /* Standard TCP port number for Ident service. Assigned by IANA */
- #define IDENT_PORT 113
- static int ident_inet(hbaPort *port);
- /*----------------------------------------------------------------
- * Peer authentication
- *----------------------------------------------------------------
- */
- static int auth_peer(hbaPort *port);
- /*----------------------------------------------------------------
- * PAM authentication
- *----------------------------------------------------------------
- */
- #ifdef USE_PAM
- #ifdef HAVE_PAM_PAM_APPL_H
- #include <pam/pam_appl.h>
- #endif
- #ifdef HAVE_SECURITY_PAM_APPL_H
- #include <security/pam_appl.h>
- #endif
- #define PGSQL_PAM_SERVICE "postgresql" /* Service name passed to PAM */
- static int CheckPAMAuth(Port *port, const char *user, const char *password);
- static int pam_passwd_conv_proc(int num_msg, const struct pam_message **msg,
- struct pam_response **resp, void *appdata_ptr);
- static struct pam_conv pam_passw_conv = {
- &pam_passwd_conv_proc,
- NULL
- };
- static const char *pam_passwd = NULL; /* Workaround for Solaris 2.6
- * brokenness */
- static Port *pam_port_cludge; /* Workaround for passing "Port *port" into
- * pam_passwd_conv_proc */
- static bool pam_no_password; /* For detecting no-password-given */
- #endif /* USE_PAM */
- /*----------------------------------------------------------------
- * BSD authentication
- *----------------------------------------------------------------
- */
- #ifdef USE_BSD_AUTH
- #include <bsd_auth.h>
- static int CheckBSDAuth(Port *port, char *user);
- #endif /* USE_BSD_AUTH */
- /*----------------------------------------------------------------
- * LDAP authentication
- *----------------------------------------------------------------
- */
- #ifdef USE_LDAP
- #ifndef WIN32
- /* We use a deprecated function to keep the codepath the same as win32. */
- #define LDAP_DEPRECATED 1
- #include <ldap.h>
- #else
- #include <winldap.h>
- /* Correct header from the Platform SDK */
- typedef
- ULONG (*__ldap_start_tls_sA) (IN PLDAP ExternalHandle,
- OUT PULONG ServerReturnValue,
- OUT LDAPMessage **result,
- IN PLDAPControlA * ServerControls,
- IN PLDAPControlA * ClientControls
- );
- #endif
- static int CheckLDAPAuth(Port *port);
- /* LDAP_OPT_DIAGNOSTIC_MESSAGE is the newer spelling */
- #ifndef LDAP_OPT_DIAGNOSTIC_MESSAGE
- #define LDAP_OPT_DIAGNOSTIC_MESSAGE LDAP_OPT_ERROR_STRING
- #endif
- #endif /* USE_LDAP */
- /*----------------------------------------------------------------
- * Cert authentication
- *----------------------------------------------------------------
- */
- #ifdef USE_SSL
- static int CheckCertAuth(Port *port);
- #endif
- /*----------------------------------------------------------------
- * Kerberos and GSSAPI GUCs
- *----------------------------------------------------------------
- */
- char *pg_krb_server_keyfile;
- bool pg_krb_caseins_users;
- /*----------------------------------------------------------------
- * GSSAPI Authentication
- *----------------------------------------------------------------
- */
- #ifdef ENABLE_GSS
- #include "libpq/be-gssapi-common.h"
- static int pg_GSS_checkauth(Port *port);
- static int pg_GSS_recvauth(Port *port);
- #endif /* ENABLE_GSS */
- /*----------------------------------------------------------------
- * SSPI Authentication
- *----------------------------------------------------------------
- */
- #ifdef ENABLE_SSPI
- typedef SECURITY_STATUS
- (WINAPI * QUERY_SECURITY_CONTEXT_TOKEN_FN) (PCtxtHandle, void **);
- static int pg_SSPI_recvauth(Port *port);
- static int pg_SSPI_make_upn(char *accountname,
- size_t accountnamesize,
- char *domainname,
- size_t domainnamesize,
- bool update_accountname);
- #endif
- /*----------------------------------------------------------------
- * RADIUS Authentication
- *----------------------------------------------------------------
- */
- static int CheckRADIUSAuth(Port *port);
- static int PerformRadiusTransaction(const char *server, const char *secret, const char *portstr, const char *identifier, const char *user_name, const char *passwd);
- /*
- * Maximum accepted size of GSS and SSPI authentication tokens.
- *
- * Kerberos tickets are usually quite small, but the TGTs issued by Windows
- * domain controllers include an authorization field known as the Privilege
- * Attribute Certificate (PAC), which contains the user's Windows permissions
- * (group memberships etc.). The PAC is copied into all tickets obtained on
- * the basis of this TGT (even those issued by Unix realms which the Windows
- * realm trusts), and can be several kB in size. The maximum token size
- * accepted by Windows systems is determined by the MaxAuthToken Windows
- * registry setting. Microsoft recommends that it is not set higher than
- * 65535 bytes, so that seems like a reasonable limit for us as well.
- */
- #define PG_MAX_AUTH_TOKEN_LENGTH 65535
- /*
- * Maximum accepted size of SASL messages.
- *
- * The messages that the server or libpq generate are much smaller than this,
- * but have some headroom.
- */
- #define PG_MAX_SASL_MESSAGE_LENGTH 1024
- /*----------------------------------------------------------------
- * Global authentication functions
- *----------------------------------------------------------------
- */
- /*
- * This hook allows plugins to get control following client authentication,
- * but before the user has been informed about the results. It could be used
- * to record login events, insert a delay after failed authentication, etc.
- */
- ClientAuthentication_hook_type ClientAuthentication_hook = NULL;
- /*
- * 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. In
- * particular, if logdetail isn't NULL, we send that string to the log.
- */
- static void
- auth_failed(Port *port, int status, char *logdetail)
- {
- const char *errstr;
- char *cdetail;
- int errcode_return = ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION;
- /*
- * 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->hba->auth_method)
- {
- case uaReject:
- case uaImplicitReject:
- errstr = gettext_noop("authentication failed for user \"%s\": host rejected");
- 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 uaPeer:
- errstr = gettext_noop("Peer authentication failed for user \"%s\"");
- break;
- case uaPassword:
- case uaMD5:
- case uaSCRAM:
- errstr = gettext_noop("password authentication failed for user \"%s\"");
- /* We use it to indicate if a .pgpass password failed. */
- errcode_return = ERRCODE_INVALID_PASSWORD;
- 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 uaPAM:
- errstr = gettext_noop("PAM authentication failed for user \"%s\"");
- break;
- case uaBSD:
- errstr = gettext_noop("BSD authentication failed for user \"%s\"");
- break;
- case uaLDAP:
- errstr = gettext_noop("LDAP authentication failed for user \"%s\"");
- break;
- case uaCert:
- errstr = gettext_noop("certificate authentication failed for user \"%s\"");
- break;
- case uaRADIUS:
- errstr = gettext_noop("RADIUS authentication failed for user \"%s\"");
- break;
- default:
- errstr = gettext_noop("authentication failed for user \"%s\": invalid authentication method");
- break;
- }
- cdetail = psprintf(_("Connection matched pg_hba.conf line %d: \"%s\""),
- port->hba->linenumber, port->hba->rawline);
- if (logdetail)
- logdetail = psprintf("%s\n%s", logdetail, cdetail);
- else
- logdetail = cdetail;
- ereport(FATAL,
- (errcode(errcode_return),
- errmsg(errstr, port->user_name),
- logdetail ? errdetail_log("%s", logdetail) : 0));
- /* doesn't return */
- }
- /*
- * 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;
- char *logdetail = NULL;
- /*
- * Get the authentication method to use for this frontend/database
- * combination. Note: we do not parse the file at this point; this has
- * already been done elsewhere. hba.c dropped an error message into the
- * server logfile if parsing the hba config file failed.
- */
- hba_getauthmethod(port);
- CHECK_FOR_INTERRUPTS();
- /*
- * This is the first point where we have access to the hba record for the
- * current connection, so perform any verifications based on the hba
- * options field that should be done *before* the authentication here.
- */
- if (port->hba->clientcert != clientCertOff)
- {
- /* If we haven't loaded a root certificate store, fail */
- if (!secure_loaded_verify_locations())
- ereport(FATAL,
- (errcode(ERRCODE_CONFIG_FILE_ERROR),
- errmsg("client certificates can only be checked if a root certificate store is available")));
- /*
- * If we loaded a root certificate store, and if a certificate is
- * present on the client, then it has been verified against our root
- * certificate store, and the connection would have been aborted
- * already if it didn't verify ok.
- */
- if (!port->peer_cert_valid)
- ereport(FATAL,
- (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
- errmsg("connection requires a valid client certificate")));
- }
- #ifdef ENABLE_GSS
- if (port->gss->enc && port->hba->auth_method != uaReject &&
- port->hba->auth_method != uaImplicitReject &&
- port->hba->auth_method != uaTrust &&
- port->hba->auth_method != uaGSS)
- {
- ereport(FATAL, (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
- errmsg("GSSAPI encryption can only be used with gss, trust, or reject authentication methods")));
- }
- #endif
- /*
- * Now proceed to do the actual authentication check
- */
- switch (port->hba->auth_method)
- {
- case uaReject:
- /*
- * An explicit "reject" entry in pg_hba.conf. This report exposes
- * the fact that there's an explicit reject entry, which is
- * perhaps not so desirable from a security standpoint; but the
- * message for an implicit reject could confuse the DBA a lot when
- * the true situation is a match to an explicit reject. And we
- * don't want to change the message for an implicit reject. As
- * noted below, the additional information shown here doesn't
- * expose anything not known to an attacker.
- */
- {
- char hostinfo[NI_MAXHOST];
- pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
- hostinfo, sizeof(hostinfo),
- NULL, 0,
- NI_NUMERICHOST);
- if (am_walsender)
- {
- #ifdef USE_SSL
- ereport(FATAL,
- (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
- errmsg("pg_hba.conf rejects replication connection for host \"%s\", user \"%s\", %s",
- hostinfo, port->user_name,
- port->ssl_in_use ? _("SSL on") : _("SSL off"))));
- #else
- ereport(FATAL,
- (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
- errmsg("pg_hba.conf rejects replication connection for host \"%s\", user \"%s\"",
- hostinfo, port->user_name)));
- #endif
- }
- else
- {
- #ifdef USE_SSL
- ereport(FATAL,
- (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
- errmsg("pg_hba.conf rejects connection for host \"%s\", user \"%s\", database \"%s\", %s",
- hostinfo, port->user_name,
- port->database_name,
- port->ssl_in_use ? _("SSL on") : _("SSL off"))));
- #else
- ereport(FATAL,
- (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
- errmsg("pg_hba.conf rejects connection for host \"%s\", user \"%s\", database \"%s\"",
- hostinfo, port->user_name,
- port->database_name)));
- #endif
- }
- break;
- }
- case uaImplicitReject:
- /*
- * No matching entry, so tell the user we fell through.
- *
- * NOTE: the extra info reported here is not a security breach,
- * because all that info is known at the frontend and must be
- * assumed known to bad guys. We're merely helping out the less
- * clueful good guys.
- */
- {
- char hostinfo[NI_MAXHOST];
- pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
- hostinfo, sizeof(hostinfo),
- NULL, 0,
- NI_NUMERICHOST);
- #define HOSTNAME_LOOKUP_DETAIL(port) \
- (port->remote_hostname ? \
- (port->remote_hostname_resolv == +1 ? \
- errdetail_log("Client IP address resolved to \"%s\", forward lookup matches.", \
- port->remote_hostname) : \
- port->remote_hostname_resolv == 0 ? \
- errdetail_log("Client IP address resolved to \"%s\", forward lookup not checked.", \
- port->remote_hostname) : \
- port->remote_hostname_resolv == -1 ? \
- errdetail_log("Client IP address resolved to \"%s\", forward lookup does not match.", \
- port->remote_hostname) : \
- port->remote_hostname_resolv == -2 ? \
- errdetail_log("Could not translate client host name \"%s\" to IP address: %s.", \
- port->remote_hostname, \
- gai_strerror(port->remote_hostname_errcode)) : \
- 0) \
- : (port->remote_hostname_resolv == -2 ? \
- errdetail_log("Could not resolve client IP address to a host name: %s.", \
- gai_strerror(port->remote_hostname_errcode)) : \
- 0))
- if (am_walsender)
- {
- #ifdef USE_SSL
- ereport(FATAL,
- (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
- errmsg("no pg_hba.conf entry for replication connection from host \"%s\", user \"%s\", %s",
- hostinfo, port->user_name,
- port->ssl_in_use ? _("SSL on") : _("SSL off")),
- HOSTNAME_LOOKUP_DETAIL(port)));
- #else
- ereport(FATAL,
- (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
- errmsg("no pg_hba.conf entry for replication connection from host \"%s\", user \"%s\"",
- hostinfo, port->user_name),
- HOSTNAME_LOOKUP_DETAIL(port)));
- #endif
- }
- else
- {
- #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_in_use ? _("SSL on") : _("SSL off")),
- HOSTNAME_LOOKUP_DETAIL(port)));
- #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),
- HOSTNAME_LOOKUP_DETAIL(port)));
- #endif
- }
- break;
- }
- case uaGSS:
- #ifdef ENABLE_GSS
- port->gss->auth = true;
- if (port->gss->enc)
- status = pg_GSS_checkauth(port);
- else
- {
- sendAuthRequest(port, AUTH_REQ_GSS, NULL, 0);
- status = pg_GSS_recvauth(port);
- }
- #else
- Assert(false);
- #endif
- break;
- case uaSSPI:
- #ifdef ENABLE_SSPI
- sendAuthRequest(port, AUTH_REQ_SSPI, NULL, 0);
- status = pg_SSPI_recvauth(port);
- #else
- Assert(false);
- #endif
- break;
- case uaPeer:
- status = auth_peer(port);
- break;
- case uaIdent:
- status = ident_inet(port);
- break;
- case uaMD5:
- case uaSCRAM:
- status = CheckPWChallengeAuth(port, &logdetail);
- break;
- case uaPassword:
- status = CheckPasswordAuth(port, &logdetail);
- break;
- case uaPAM:
- #ifdef USE_PAM
- status = CheckPAMAuth(port, port->user_name, "");
- #else
- Assert(false);
- #endif /* USE_PAM */
- break;
- case uaBSD:
- #ifdef USE_BSD_AUTH
- status = CheckBSDAuth(port, port->user_name);
- #else
- Assert(false);
- #endif /* USE_BSD_AUTH */
- break;
- case uaLDAP:
- #ifdef USE_LDAP
- status = CheckLDAPAuth(port);
- #else
- Assert(false);
- #endif
- break;
- case uaRADIUS:
- status = CheckRADIUSAuth(port);
- break;
- case uaCert:
- /* uaCert will be treated as if clientcert=verify-full (uaTrust) */
- case uaTrust:
- status = STATUS_OK;
- break;
- }
- if ((status == STATUS_OK && port->hba->clientcert == clientCertFull)
- || port->hba->auth_method == uaCert)
- {
- /*
- * Make sure we only check the certificate if we use the cert method
- * or verify-full option.
- */
- #ifdef USE_SSL
- status = CheckCertAuth(port);
- #else
- Assert(false);
- #endif
- }
- if (ClientAuthentication_hook)
- (*ClientAuthentication_hook) (port, status);
- if (status == STATUS_OK)
- sendAuthRequest(port, AUTH_REQ_OK, NULL, 0);
- else
- auth_failed(port, status, logdetail);
- }
- /*
- * Send an authentication request packet to the frontend.
- */
- static void
- sendAuthRequest(Port *port, AuthRequest areq, const char *extradata, int extralen)
- {
- StringInfoData buf;
- CHECK_FOR_INTERRUPTS();
- pq_beginmessage(&buf, 'R');
- pq_sendint32(&buf, (int32) areq);
- if (extralen > 0)
- pq_sendbytes(&buf, extradata, extralen);
- pq_endmessage(&buf);
- /*
- * Flush message so client will see it, except for AUTH_REQ_OK and
- * AUTH_REQ_SASL_FIN, which need not be sent until we are ready for
- * queries.
- */
- if (areq != AUTH_REQ_OK && areq != AUTH_REQ_SASL_FIN)
- pq_flush();
- CHECK_FOR_INTERRUPTS();
- }
- /*
- * 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;
- pq_startmsgread();
- 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(ERROR,
- (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(ERROR,
- (errcode(ERRCODE_PROTOCOL_VIOLATION),
- errmsg("invalid password packet size")));
- /*
- * Don't allow an empty password. Libpq treats an empty password the same
- * as no password at all, and won't even try to authenticate. But other
- * clients might, so allowing it would be confusing.
- *
- * Note that this only catches an empty password sent by the client in
- * plaintext. There's also a check in CREATE/ALTER USER that prevents an
- * empty string from being stored as a user's password in the first place.
- * We rely on that for MD5 and SCRAM authentication, but we still need
- * this check here, to prevent an empty password from being used with
- * authentication methods that check the password against an external
- * system, like PAM, LDAP and RADIUS.
- */
- if (buf.len == 1)
- ereport(ERROR,
- (errcode(ERRCODE_INVALID_PASSWORD),
- errmsg("empty password returned by client")));
- /* Do not echo password to logs, for security. */
- elog(DEBUG5, "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;
- }
- /*----------------------------------------------------------------
- * Password-based authentication mechanisms
- *----------------------------------------------------------------
- */
- /*
- * Plaintext password authentication.
- */
- static int
- CheckPasswordAuth(Port *port, char **logdetail)
- {
- char *passwd;
- int result;
- char *shadow_pass;
- sendAuthRequest(port, AUTH_REQ_PASSWORD, NULL, 0);
- passwd = recv_password_packet(port);
- if (passwd == NULL)
- return STATUS_EOF; /* client wouldn't send password */
- shadow_pass = get_role_password(port->user_name, logdetail);
- if (shadow_pass)
- {
- result = plain_crypt_verify(port->user_name, shadow_pass, passwd,
- logdetail);
- }
- else
- result = STATUS_ERROR;
- if (shadow_pass)
- pfree(shadow_pass);
- pfree(passwd);
- return result;
- }
- /*
- * MD5 and SCRAM authentication.
- */
- static int
- CheckPWChallengeAuth(Port *port, char **logdetail)
- {
- int auth_result;
- char *shadow_pass;
- PasswordType pwtype;
- Assert(port->hba->auth_method == uaSCRAM ||
- port->hba->auth_method == uaMD5);
- /* First look up the user's password. */
- shadow_pass = get_role_password(port->user_name, logdetail);
- /*
- * If the user does not exist, or has no password or it's expired, we
- * still go through the motions of authentication, to avoid revealing to
- * the client that the user didn't exist. If 'md5' is allowed, we choose
- * whether to use 'md5' or 'scram-sha-256' authentication based on current
- * password_encryption setting. The idea is that most genuine users
- * probably have a password of that type, and if we pretend that this user
- * had a password of that type, too, it "blends in" best.
- */
- if (!shadow_pass)
- pwtype = Password_encryption;
- else
- pwtype = get_password_type(shadow_pass);
- /*
- * If 'md5' authentication is allowed, decide whether to perform 'md5' or
- * 'scram-sha-256' authentication based on the type of password the user
- * has. If it's an MD5 hash, we must do MD5 authentication, and if it's a
- * SCRAM secret, we must do SCRAM authentication.
- *
- * If MD5 authentication is not allowed, always use SCRAM. If the user
- * had an MD5 password, CheckSCRAMAuth() will fail.
- */
- if (port->hba->auth_method == uaMD5 && pwtype == PASSWORD_TYPE_MD5)
- auth_result = CheckMD5Auth(port, shadow_pass, logdetail);
- else
- auth_result = CheckSCRAMAuth(port, shadow_pass, logdetail);
- if (shadow_pass)
- pfree(shadow_pass);
- /*
- * If get_role_password() returned error, return error, even if the
- * authentication succeeded.
- */
- if (!shadow_pass)
- {
- Assert(auth_result != STATUS_OK);
- return STATUS_ERROR;
- }
- return auth_result;
- }
- static int
- CheckMD5Auth(Port *port, char *shadow_pass, char **logdetail)
- {
- char md5Salt[4]; /* Password salt */
- char *passwd;
- int result;
- if (Db_user_namespace)
- ereport(FATAL,
- (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
- errmsg("MD5 authentication is not supported when \"db_user_namespace\" is enabled")));
- /* include the salt to use for computing the response */
- if (!pg_strong_random(md5Salt, 4))
- {
- ereport(LOG,
- (errmsg("could not generate random MD5 salt")));
- return STATUS_ERROR;
- }
- sendAuthRequest(port, AUTH_REQ_MD5, md5Salt, 4);
- passwd = recv_password_packet(port);
- if (passwd == NULL)
- return STATUS_EOF; /* client wouldn't send password */
- if (shadow_pass)
- result = md5_crypt_verify(port->user_name, shadow_pass, passwd,
- md5Salt, 4, logdetail);
- else
- result = STATUS_ERROR;
- pfree(passwd);
- return result;
- }
- static int
- CheckSCRAMAuth(Port *port, char *shadow_pass, char **logdetail)
- {
- StringInfoData sasl_mechs;
- int mtype;
- StringInfoData buf;
- void *scram_opaq = NULL;
- char *output = NULL;
- int outputlen = 0;
- const char *input;
- int inputlen;
- int result;
- bool initial;
- /*
- * SASL auth is not supported for protocol versions before 3, because it
- * relies on the overall message length word to determine the SASL payload
- * size in AuthenticationSASLContinue and PasswordMessage messages. (We
- * used to have a hard rule that protocol messages must be parsable
- * without relying on the length word, but we hardly care about older
- * protocol version anymore.)
- */
- if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
- ereport(FATAL,
- (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
- errmsg("SASL authentication is not supported in protocol version 2")));
- /*
- * Send the SASL authentication request to user. It includes the list of
- * authentication mechanisms that are supported.
- */
- initStringInfo(&sasl_mechs);
- pg_be_scram_get_mechanisms(port, &sasl_mechs);
- /* Put another '\0' to mark that list is finished. */
- appendStringInfoChar(&sasl_mechs, '\0');
- sendAuthRequest(port, AUTH_REQ_SASL, sasl_mechs.data, sasl_mechs.len);
- pfree(sasl_mechs.data);
- /*
- * Loop through SASL message exchange. This exchange can consist of
- * multiple messages sent in both directions. First message is always
- * from the client. All messages from client to server are password
- * packets (type 'p').
- */
- initial = true;
- do
- {
- pq_startmsgread();
- mtype = pq_getbyte();
- if (mtype != 'p')
- {
- /* Only log error if client didn't disconnect. */
- if (mtype != EOF)
- {
- ereport(ERROR,
- (errcode(ERRCODE_PROTOCOL_VIOLATION),
- errmsg("expected SASL response, got message type %d",
- mtype)));
- }
- else
- return STATUS_EOF;
- }
- /* Get the actual SASL message */
- initStringInfo(&buf);
- if (pq_getmessage(&buf, PG_MAX_SASL_MESSAGE_LENGTH))
- {
- /* EOF - pq_getmessage already logged error */
- pfree(buf.data);
- return STATUS_ERROR;
- }
- elog(DEBUG4, "processing received SASL response of length %d", buf.len);
- /*
- * The first SASLInitialResponse message is different from the others.
- * It indicates which SASL mechanism the client selected, and contains
- * an optional Initial Client Response payload. The subsequent
- * SASLResponse messages contain just the SASL payload.
- */
- if (initial)
- {
- const char *selected_mech;
- selected_mech = pq_getmsgrawstring(&buf);
- /*
- * Initialize the status tracker for message exchanges.
- *
- * If the user doesn't exist, or doesn't have a valid password, or
- * it's expired, we still go through the motions of SASL
- * authentication, but tell the authentication method that the
- * authentication is "doomed". That is, it's going to fail, no
- * matter what.
- *
- * This is because we don't want to reveal to an attacker what
- * usernames are valid, nor which users have a valid password.
- */
- scram_opaq = pg_be_scram_init(port, selected_mech, shadow_pass);
- inputlen = pq_getmsgint(&buf, 4);
- if (inputlen == -1)
- input = NULL;
- else
- input = pq_getmsgbytes(&buf, inputlen);
- initial = false;
- }
- else
- {
- inputlen = buf.len;
- input = pq_getmsgbytes(&buf, buf.len);
- }
- pq_getmsgend(&buf);
- /*
- * The StringInfo guarantees that there's a \0 byte after the
- * response.
- */
- Assert(input == NULL || input[inputlen] == '\0');
- /*
- * we pass 'logdetail' as NULL when doing a mock authentication,
- * because we should already have a better error message in that case
- */
- result = pg_be_scram_exchange(scram_opaq, input, inputlen,
- &output, &outputlen,
- logdetail);
- /* input buffer no longer used */
- pfree(buf.data);
- if (output)
- {
- /*
- * Negotiation generated data to be sent to the client.
- */
- elog(DEBUG4, "sending SASL challenge of length %u", outputlen);
- if (result == SASL_EXCHANGE_SUCCESS)
- sendAuthRequest(port, AUTH_REQ_SASL_FIN, output, outputlen);
- else
- sendAuthRequest(port, AUTH_REQ_SASL_CONT, output, outputlen);
- pfree(output);
- }
- } while (result == SASL_EXCHANGE_CONTINUE);
- /* Oops, Something bad happened */
- if (result != SASL_EXCHANGE_SUCCESS)
- {
- return STATUS_ERROR;
- }
- return STATUS_OK;
- }
- /*----------------------------------------------------------------
- * GSSAPI authentication system
- *----------------------------------------------------------------
- */
- #ifdef ENABLE_GSS
- static int
- pg_GSS_recvauth(Port *port)
- {
- OM_uint32 maj_stat,
- min_stat,
- lmin_s,
- gflags;
- int mtype;
- StringInfoData buf;
- gss_buffer_desc gbuf;
- /*
- * 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 ||
- snprintf(kt_path, kt_len, "KRB5_KTNAME=%s",
- pg_krb_server_keyfile) != kt_len - 2 ||
- putenv(kt_path) != 0)
- {
- ereport(LOG,
- (errcode(ERRCODE_OUT_OF_MEMORY),
- errmsg("out of memory")));
- return STATUS_ERROR;
- }
- }
- }
- /*
- * 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 messages sent in both directions. First message is always from
- * the client. All messages from client to server are password packets
- * (type 'p').
- */
- do
- {
- pq_startmsgread();
- CHECK_FOR_INTERRUPTS();
- mtype = pq_getbyte();
- if (mtype != 'p')
- {
- /* Only log error if client didn't disconnect. */
- if (mtype != EOF)
- ereport(ERROR,
- (errcode(ERRCODE_PROTOCOL_VIOLATION),
- errmsg("expected GSS response, got message type %d",
- mtype)));
- return STATUS_ERROR;
- }
- /* Get the actual GSS token */
- initStringInfo(&buf);
- if (pq_getmessage(&buf, PG_MAX_AUTH_TOKEN_LENGTH))
- {
- /* EOF - pq_getmessage already logged error */
- pfree(buf.data);
- return STATUS_ERROR;
- }
- /* Map to GSSAPI style buffer */
- gbuf.length = buf.len;
- gbuf.value = buf.data;
- elog(DEBUG4, "processing received GSS token of length %u",
- (unsigned int) gbuf.length);
- maj_stat = gss_accept_sec_context(&min_stat,
- &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, "
- "minor: %d, outlen: %u, outflags: %x",
- maj_stat, min_stat,
- (unsigned int) port->gss->outbuf.length, gflags);
- CHECK_FOR_INTERRUPTS();
- if (port->gss->outbuf.length != 0)
- {
- /*
- * Negotiation generated data to be sent to the client.
- */
- elog(DEBUG4, "sending GSS response token of length %u",
- (unsigned int) port->gss->outbuf.length);
- sendAuthRequest(port, AUTH_REQ_GSS_CONT,
- port->gss->outbuf.value, port->gss->outbuf.length);
- gss_release_buffer(&lmin_s, &port->gss->outbuf);
- }
- if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
- {
- gss_delete_sec_context(&lmin_s, &port->gss->ctx, GSS_C_NO_BUFFER);
- pg_GSS_error(ERROR,
- _("accepting GSS security context failed"),
- maj_stat, min_stat);
- }
- if (maj_stat == GSS_S_CONTINUE_NEEDED)
- elog(DEBUG4, "GSS continue needed");
- } while (maj_stat == GSS_S_CONTINUE_NEEDED);
- if (port->gss->cred != GSS_C_NO_CREDENTIAL)
- {
- /*
- * Release service principal credentials
- */
- gss_release_cred(&min_stat, &port->gss->cred);
- }
- return pg_GSS_checkauth(port);
- }
- /*
- * Check whether the GSSAPI-authenticated user is allowed to connect as the
- * claimed username.
- */
- static int
- pg_GSS_checkauth(Port *port)
- {
- int ret;
- OM_uint32 maj_stat,
- min_stat,
- lmin_s;
- gss_buffer_desc gbuf;
- /*
- * 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,
- _("retrieving GSS user name failed"),
- maj_stat, min_stat);
- /*
- * Copy the original name of the authenticated principal into our backend
- * memory for display later.
- */
- port->gss->princ = MemoryContextStrdup(TopMemoryContext, gbuf.value);
- /*
- * Split the username at the realm separator
- */
- if (strchr(gbuf.value, '@'))
- {
- char *cp = strchr(gbuf.value, '@');
- /*
- * If we are not going to include the realm in the username that is
- * passed to the ident map, destructively modify it here to remove the
- * realm. Then advance past the separator to check the realm.
- */
- if (!port->hba->include_realm)
- *cp = '\0';
- cp++;
- if (port->hba->krb_realm != NULL && strlen(port->hba->krb_realm))
- {
- /*
- * Match the realm part of the name first
- */
- if (pg_krb_caseins_users)
- ret = pg_strcasecmp(port->hba->krb_realm, cp);
- else
- ret = strcmp(port->hba->krb_realm, cp);
- if (ret)
- {
- /* GSS realm does not match */
- elog(DEBUG2,
- "GSSAPI realm (%s) and configured realm (%s) don't match",
- cp, port->hba->krb_realm);
- gss_release_buffer(&lmin_s, &gbuf);
- return STATUS_ERROR;
- }
- }
- }
- else if (port->hba->krb_realm && strlen(port->hba->krb_realm))
- {
- elog(DEBUG2,
- "GSSAPI did not return realm but realm matching was requested");
- gss_release_buffer(&lmin_s, &gbuf);
- return STATUS_ERROR;
- }
- ret = check_usermap(port->hba->usermap, port->user_name, gbuf.value,
- pg_krb_caseins_users);
- gss_release_buffer(&lmin_s, &gbuf);
- return ret;
- }
- #endif /* ENABLE_GSS */
- /*----------------------------------------------------------------
- * SSPI authentication system
- *----------------------------------------------------------------
- */
- #ifdef ENABLE_SSPI
- /*
- * Generate an error for SSPI authentication. The caller should apply
- * _() to errmsg to make it translatable.
- */
- static void
- pg_SSPI_error(int severity, const char *errmsg, SECURITY_STATUS r)
- {
- char sysmsg[256];
- if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
- FORMAT_MESSAGE_FROM_SYSTEM,
- NULL, r, 0,
- sysmsg, sizeof(sysmsg), NULL) == 0)
- ereport(severity,
- (errmsg_internal("%s", errmsg),
- errdetail_internal("SSPI error %x", (unsigned int) r)));
- else
- ereport(severity,
- (errmsg_internal("%s", errmsg),
- errdetail_internal("%s (%x)", sysmsg, (unsigned int) r)));
- }
- static int
- pg_SSPI_recvauth(Port *port)
- {
- 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;
- /*
- * SSPI auth is not supported for protocol versions before 3, because it
- * relies on the overall message length word to determine the SSPI payload
- * size in AuthenticationGSSContinue and PasswordMessage messages. (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 (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
- ereport(FATAL,
- (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
- errmsg("SSPI is not supported in protocol version 2")));
- /*
- * Acquire a handle to the server credentials.
- */
- r = AcquireCredentialsHandle(NULL,
- "negotiate",
- SECPKG_CRED_INBOUND,
- NULL,
- NULL,
- NULL,
- NULL,
- &sspicred,
- &expiry);
- if (r != SEC_E_OK)
- pg_SSPI_error(ERROR, _("could not acquire SSPI credentials"), r);
- /*
- * Loop through SSPI message exchange. This exchange can consist of
- * multiple messages sent in both directions. First message is always from
- * the client. All messages from client to server are password packets
- * (type 'p').
- */
- do
- {
- pq_startmsgread();
- mtype = pq_getbyte();
- if (mtype != 'p')
- {
- if (sspictx != NULL)
- {
- DeleteSecurityContext(sspictx);
- free(sspictx);
- }
- FreeCredentialsHandle(&sspicred);
- /* Only log error if client didn't disconnect. */
- if (mtype != EOF)
- ereport(ERROR,
- (errcode(ERRCODE_PROTOCOL_VIOLATION),
- errmsg("expected SSPI response, got message type %d",
- mtype)));
- return STATUS_ERROR;
- }
- /* Get the actual SSPI token */
- initStringInfo(&buf);
- if (pq_getmessage(&buf, PG_MAX_AUTH_TOKEN_LENGTH))
- {
- /* EOF - pq_getmessage already logged error */
- pfree(buf.data);
- if (sspictx != NULL)
- {
- DeleteSecurityContext(sspictx);
- free(sspictx);
- }
- FreeCredentialsHandle(&sspicred);
- return STATUS_ERROR;
- }
- /* Map to SSPI style buffer */
- inbuf.ulVersion = SECBUFFER_VERSION;
- inbuf.cBuffers = 1;
- 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",
- (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)
- {
- /*
- * Negotiation generated data to be sent to the client.
- */
- elog(DEBUG4, "sending SSPI response token of length %u",
- (unsigned int) outbuf.pBuffers[0].cbBuffer);
- port->gss->outbuf.length = outbuf.pBuffers[0].cbBuffer;
- port->gss->outbuf.value = outbuf.pBuffers[0].pvBuffer;
- sendAuthRequest(port, AUTH_REQ_GSS_CONT,
- port->gss->outbuf.value, port->gss->outbuf.length);
- FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
- }
- if (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)
- {
- if (sspictx != NULL)
- {
- DeleteSecurityContext(sspictx);
- free(sspictx);
- }
- FreeCredentialsHandle(&sspicred);
- pg_SSPI_error(ERROR,
- _("could not accept SSPI security context"), r);
- }
- /*
- * Overwrite the current context with the one we just received. If
- * sspictx is NULL it was the first loop and we need to allocate a
- * buffer for it. On subsequent runs, we can just overwrite the buffer
- * contents since the size does not change.
- */
- if (sspictx == NULL)
- {
- sspictx = malloc(sizeof(CtxtHandle));
- if (sspictx == NULL)
- ereport(ERROR,
- (errmsg("out of memory")));
- }
- memcpy(sspictx, &newctx, sizeof(CtxtHandle));
- if (r == SEC_I_CONTINUE_NEEDED)
- elog(DEBUG4, "SSPI continue needed");
- } while (r == SEC_I_CONTINUE_NEEDED);
- /*
- * Release service principal credentials
- */
- FreeCredentialsHandle(&sspicred);
- /*
- * SEC_E_OK 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.
- *
- * MingW is missing the export for QuerySecurityContextToken in the
- * secur32 library, so we have to load it dynamically.
- */
- secur32 = LoadLibrary("SECUR32.DLL");
- if (secur32 == NULL)
- ereport(ERROR,
- (errmsg("could not load library \"%s\": error code %lu",
- "SECUR32.DLL", 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: error code %lu",
- GetLastError())));
- }
- r = (_QuerySecurityContextToken) (sspictx, &token);
- if (r != SEC_E_OK)
- {
- FreeLibrary(secur32);
- pg_SSPI_error(ERROR,
- _("could not get token from SSPI security context"), r);
- }
- FreeLibrary(secur32);
- /*
- * No longer need the security context, everything from here on uses the
- * token instead.
- */
- DeleteSecurityContext(sspictx);
- free(sspictx);
- if (!GetTokenInformation(token, TokenUser, NULL, 0, &retlen) && GetLastError() != 122)
- ereport(ERROR,
- (errmsg_internal("could not get token information buffer size: error code %lu",
- 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 token information: error code %lu",
- GetLastError())));
- CloseHandle(token);
- if (!LookupAccountSid(NULL, tokenuser->User.Sid, accountname, &accountnamesize,
- domainname, &domainnamesize, &accountnameuse))
- ereport(ERROR,
- (errmsg_internal("could not look up account SID: error code %lu",
- GetLastError())));
- free(tokenuser);
- if (!port->hba->compat_realm)
- {
- int status = pg_SSPI_make_upn(accountname, sizeof(accountname),
- domainname, sizeof(domainname),
- port->hba->upn_username);
- if (status != STATUS_OK)
- /* Error already reported from pg_SSPI_make_upn */
- return status;
- }
- /*
- * Compare realm/domain if requested. In SSPI, always compare case
- * insensitive.
- */
- if (port->hba->krb_realm && strlen(port->hba->krb_realm))
- {
- if (pg_strcasecmp(port->hba->krb_realm, domainname) != 0)
- {
- elog(DEBUG2,
- "SSPI domain (%s) and configured domain (%s) don't match",
- domainname, port->hba->krb_realm);
- return STATUS_ERROR;
- }
- }
- /*
- * We have the username (without domain/realm) in accountname, compare to
- * the supplied value. In SSPI, always compare case insensitive.
- *
- * If set to include realm, append it in <username>@<realm> format.
- */
- if (port->hba->include_realm)
- {
- char *namebuf;
- int retval;
- namebuf = psprintf("%s@%s", accountname, domainname);
- retval = check_usermap(port->hba->usermap, port->user_name, namebuf, true);
- pfree(namebuf);
- return retval;
- }
- else
- return check_usermap(port->hba->usermap, port->user_name, accountname, true);
- }
- /*
- * Replaces the domainname with the Kerberos realm name,
- * and optionally the accountname with the Kerberos user name.
- */
- static int
- pg_SSPI_make_upn(char *accountname,
- size_t accountnamesize,
- char *domainname,
- size_t domainnamesize,
- bool update_accountname)
- {
- char *samname;
- char *upname = NULL;
- char *p = NULL;
- ULONG upnamesize = 0;
- size_t upnamerealmsize;
- BOOLEAN res;
- /*
- * Build SAM name (DOMAIN\user), then translate to UPN
- * (user@kerberos.realm). The realm name is returned in lower case, but
- * that is fine because in SSPI auth, string comparisons are always
- * case-insensitive.
- */
- samname = psprintf("%s\\%s", domainname, accountname);
- res = TranslateName(samname, NameSamCompatible, NameUserPrincipal,
- NULL, &upnamesize);
- if ((!res && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
- || upnamesize == 0)
- {
- pfree(samname);
- ereport(LOG,
- (errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
- errmsg("could not translate name")));
- return STATUS_ERROR;
- }
- /* upnamesize includes the terminating NUL. */
- upname = palloc(upnamesize);
- res = TranslateName(samname, NameSamCompatible, NameUserPrincipal,
- upname, &upnamesize);
- pfree(samname);
- if (res)
- p = strchr(upname, '@');
- if (!res || p == NULL)
- {
- pfree(upname);
- ereport(LOG,
- (errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
- errmsg("could not translate name")));
- return STATUS_ERROR;
- }
- /* Length of realm name after the '@', including the NUL. */
- upnamerealmsize = upnamesize - (p - upname + 1);
- /* Replace domainname with realm name. */
- if (upnamerealmsize > domainnamesize)
- {
- pfree(upname);
- ereport(LOG,
- (errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
- errmsg("realm name too long")));
- return STATUS_ERROR;
- }
- /* Length is now safe. */
- strcpy(domainname, p + 1);
- /* Replace account name as well (in case UPN != SAM)? */
- if (update_accountname)
- {
- if ((p - upname + 1) > accountnamesize)
- {
- pfree(upname);
- ereport(LOG,
- (errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
- errmsg("translated account name too long")));
- return STATUS_ERROR;
- }
- *p = 0;
- strcpy(accountname, upname);
- }
- pfree(upname);
- return STATUS_OK;
- }
- #endif /* ENABLE_SSPI */
- /*----------------------------------------------------------------
- * Ident authentication system
- *----------------------------------------------------------------
- */
- /*
- * Parse the string "*ident_response" as a response from a query to an Ident
- * server. If it's a normal response indicating a user name, return true
- * and store the user name at *ident_user. If it's anything else,
- * return false.
- */
- static bool
- interpret_ident_response(const char *ident_response,
- char *ident_user)
- {
- const char *cursor = ident_response; /* Cursor into *ident_response */
- /*
- * Ident's response, in the telnet tradition, should end in crlf (\r\n).
- */
- if (strlen(ident_response) < 2)
- return false;
- else if (ident_response[strlen(ident_response) - 2] != '\r')
- return false;
- else
- {
- while (*cursor != ':' && *cursor != '\r')
- cursor++; /* skip port field */
- if (*cursor != ':')
- return false;
- else
- {
- /* We're positioned to colon before response type field */
- char response_type[80];
- int i; /* Index into *response_type */
- cursor++; /* Go over colon */
- while (pg_isblank(*cursor))
- cursor++; /* skip blanks */
- i = 0;
- while (*cursor != ':' && *cursor != '\r' && !pg_isblank(*cursor) &&
- i < (int) (sizeof(response_type) - 1))
- response_type[i++] = *cursor++;
- response_type[i] = '\0';
- while (pg_isblank(*cursor))
- cursor++; /* skip blanks */
- if (strcmp(response_type, "USERID") != 0)
- return false;
- else
- {
- /*
- * It's a USERID response. Good. "cursor" should be pointing
- * to the colon that p…
Large files files are truncated, but you can click here to view the full file