LCOV - code coverage report
Current view: top level - src/backend/libpq - auth.c (source / functions) Hit Total Coverage
Test: PostgreSQL 12beta2 Lines: 246 774 31.8 %
Date: 2019-06-18 07:06:57 Functions: 12 21 57.1 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * auth.c
       4             :  *    Routines to handle network authentication
       5             :  *
       6             :  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/libpq/auth.c
      12             :  *
      13             :  *-------------------------------------------------------------------------
      14             :  */
      15             : 
      16             : #include "postgres.h"
      17             : 
      18             : #include <sys/param.h>
      19             : #include <sys/socket.h>
      20             : #include <netinet/in.h>
      21             : #include <unistd.h>
      22             : #ifdef HAVE_SYS_SELECT_H
      23             : #include <sys/select.h>
      24             : #endif
      25             : 
      26             : #include "commands/user.h"
      27             : #include "common/ip.h"
      28             : #include "common/md5.h"
      29             : #include "common/scram-common.h"
      30             : #include "libpq/auth.h"
      31             : #include "libpq/crypt.h"
      32             : #include "libpq/libpq.h"
      33             : #include "libpq/pqformat.h"
      34             : #include "libpq/scram.h"
      35             : #include "miscadmin.h"
      36             : #include "port/pg_bswap.h"
      37             : #include "replication/walsender.h"
      38             : #include "storage/ipc.h"
      39             : #include "utils/memutils.h"
      40             : #include "utils/timestamp.h"
      41             : 
      42             : 
      43             : /*----------------------------------------------------------------
      44             :  * Global authentication functions
      45             :  *----------------------------------------------------------------
      46             :  */
      47             : static void sendAuthRequest(Port *port, AuthRequest areq, const char *extradata,
      48             :                             int extralen);
      49             : static void auth_failed(Port *port, int status, char *logdetail);
      50             : static char *recv_password_packet(Port *port);
      51             : 
      52             : 
      53             : /*----------------------------------------------------------------
      54             :  * Password-based authentication methods (password, md5, and scram-sha-256)
      55             :  *----------------------------------------------------------------
      56             :  */
      57             : static int  CheckPasswordAuth(Port *port, char **logdetail);
      58             : static int  CheckPWChallengeAuth(Port *port, char **logdetail);
      59             : 
      60             : static int  CheckMD5Auth(Port *port, char *shadow_pass, char **logdetail);
      61             : static int  CheckSCRAMAuth(Port *port, char *shadow_pass, char **logdetail);
      62             : 
      63             : 
      64             : /*----------------------------------------------------------------
      65             :  * Ident authentication
      66             :  *----------------------------------------------------------------
      67             :  */
      68             : /* Max size of username ident server can return */
      69             : #define IDENT_USERNAME_MAX 512
      70             : 
      71             : /* Standard TCP port number for Ident service.  Assigned by IANA */
      72             : #define IDENT_PORT 113
      73             : 
      74             : static int  ident_inet(hbaPort *port);
      75             : 
      76             : #ifdef HAVE_UNIX_SOCKETS
      77             : static int  auth_peer(hbaPort *port);
      78             : #endif
      79             : 
      80             : 
      81             : /*----------------------------------------------------------------
      82             :  * PAM authentication
      83             :  *----------------------------------------------------------------
      84             :  */
      85             : #ifdef USE_PAM
      86             : #ifdef HAVE_PAM_PAM_APPL_H
      87             : #include <pam/pam_appl.h>
      88             : #endif
      89             : #ifdef HAVE_SECURITY_PAM_APPL_H
      90             : #include <security/pam_appl.h>
      91             : #endif
      92             : 
      93             : #define PGSQL_PAM_SERVICE "postgresql"    /* Service name passed to PAM */
      94             : 
      95             : static int  CheckPAMAuth(Port *port, const char *user, const char *password);
      96             : static int  pam_passwd_conv_proc(int num_msg, const struct pam_message **msg,
      97             :                                  struct pam_response **resp, void *appdata_ptr);
      98             : 
      99             : static struct pam_conv pam_passw_conv = {
     100             :     &pam_passwd_conv_proc,
     101             :     NULL
     102             : };
     103             : 
     104             : static const char *pam_passwd = NULL;   /* Workaround for Solaris 2.6
     105             :                                          * brokenness */
     106             : static Port *pam_port_cludge;   /* Workaround for passing "Port *port" into
     107             :                                  * pam_passwd_conv_proc */
     108             : #endif                          /* USE_PAM */
     109             : 
     110             : 
     111             : /*----------------------------------------------------------------
     112             :  * BSD authentication
     113             :  *----------------------------------------------------------------
     114             :  */
     115             : #ifdef USE_BSD_AUTH
     116             : #include <bsd_auth.h>
     117             : 
     118             : static int  CheckBSDAuth(Port *port, char *user);
     119             : #endif                          /* USE_BSD_AUTH */
     120             : 
     121             : 
     122             : /*----------------------------------------------------------------
     123             :  * LDAP authentication
     124             :  *----------------------------------------------------------------
     125             :  */
     126             : #ifdef USE_LDAP
     127             : #ifndef WIN32
     128             : /* We use a deprecated function to keep the codepath the same as win32. */
     129             : #define LDAP_DEPRECATED 1
     130             : #include <ldap.h>
     131             : #else
     132             : #include <winldap.h>
     133             : 
     134             : /* Correct header from the Platform SDK */
     135             : typedef
     136             : ULONG       (*__ldap_start_tls_sA) (
     137             :                                     IN PLDAP ExternalHandle,
     138             :                                     OUT PULONG ServerReturnValue,
     139             :                                     OUT LDAPMessage **result,
     140             :                                     IN PLDAPControlA * ServerControls,
     141             :                                     IN PLDAPControlA * ClientControls
     142             : );
     143             : #endif
     144             : 
     145             : static int  CheckLDAPAuth(Port *port);
     146             : 
     147             : /* LDAP_OPT_DIAGNOSTIC_MESSAGE is the newer spelling */
     148             : #ifndef LDAP_OPT_DIAGNOSTIC_MESSAGE
     149             : #define LDAP_OPT_DIAGNOSTIC_MESSAGE LDAP_OPT_ERROR_STRING
     150             : #endif
     151             : 
     152             : #endif                          /* USE_LDAP */
     153             : 
     154             : /*----------------------------------------------------------------
     155             :  * Cert authentication
     156             :  *----------------------------------------------------------------
     157             :  */
     158             : #ifdef USE_SSL
     159             : static int  CheckCertAuth(Port *port);
     160             : #endif
     161             : 
     162             : 
     163             : /*----------------------------------------------------------------
     164             :  * Kerberos and GSSAPI GUCs
     165             :  *----------------------------------------------------------------
     166             :  */
     167             : char       *pg_krb_server_keyfile;
     168             : bool        pg_krb_caseins_users;
     169             : 
     170             : 
     171             : /*----------------------------------------------------------------
     172             :  * GSSAPI Authentication
     173             :  *----------------------------------------------------------------
     174             :  */
     175             : #ifdef ENABLE_GSS
     176             : #include "libpq/be-gssapi-common.h"
     177             : 
     178             : static int  pg_GSS_checkauth(Port *port);
     179             : static int  pg_GSS_recvauth(Port *port);
     180             : #endif                          /* ENABLE_GSS */
     181             : 
     182             : 
     183             : /*----------------------------------------------------------------
     184             :  * SSPI Authentication
     185             :  *----------------------------------------------------------------
     186             :  */
     187             : #ifdef ENABLE_SSPI
     188             : typedef SECURITY_STATUS
     189             :             (WINAPI * QUERY_SECURITY_CONTEXT_TOKEN_FN) (
     190             :                                                         PCtxtHandle, void **);
     191             : static int  pg_SSPI_recvauth(Port *port);
     192             : static int  pg_SSPI_make_upn(char *accountname,
     193             :                              size_t accountnamesize,
     194             :                              char *domainname,
     195             :                              size_t domainnamesize,
     196             :                              bool update_accountname);
     197             : #endif
     198             : 
     199             : /*----------------------------------------------------------------
     200             :  * RADIUS Authentication
     201             :  *----------------------------------------------------------------
     202             :  */
     203             : static int  CheckRADIUSAuth(Port *port);
     204             : static int  PerformRadiusTransaction(const char *server, const char *secret, const char *portstr, const char *identifier, const char *user_name, const char *passwd);
     205             : 
     206             : 
     207             : /*
     208             :  * Maximum accepted size of GSS and SSPI authentication tokens.
     209             :  *
     210             :  * Kerberos tickets are usually quite small, but the TGTs issued by Windows
     211             :  * domain controllers include an authorization field known as the Privilege
     212             :  * Attribute Certificate (PAC), which contains the user's Windows permissions
     213             :  * (group memberships etc.). The PAC is copied into all tickets obtained on
     214             :  * the basis of this TGT (even those issued by Unix realms which the Windows
     215             :  * realm trusts), and can be several kB in size. The maximum token size
     216             :  * accepted by Windows systems is determined by the MaxAuthToken Windows
     217             :  * registry setting. Microsoft recommends that it is not set higher than
     218             :  * 65535 bytes, so that seems like a reasonable limit for us as well.
     219             :  */
     220             : #define PG_MAX_AUTH_TOKEN_LENGTH    65535
     221             : 
     222             : /*
     223             :  * Maximum accepted size of SASL messages.
     224             :  *
     225             :  * The messages that the server or libpq generate are much smaller than this,
     226             :  * but have some headroom.
     227             :  */
     228             : #define PG_MAX_SASL_MESSAGE_LENGTH  1024
     229             : 
     230             : /*----------------------------------------------------------------
     231             :  * Global authentication functions
     232             :  *----------------------------------------------------------------
     233             :  */
     234             : 
     235             : /*
     236             :  * This hook allows plugins to get control following client authentication,
     237             :  * but before the user has been informed about the results.  It could be used
     238             :  * to record login events, insert a delay after failed authentication, etc.
     239             :  */
     240             : ClientAuthentication_hook_type ClientAuthentication_hook = NULL;
     241             : 
     242             : /*
     243             :  * Tell the user the authentication failed, but not (much about) why.
     244             :  *
     245             :  * There is a tradeoff here between security concerns and making life
     246             :  * unnecessarily difficult for legitimate users.  We would not, for example,
     247             :  * want to report the password we were expecting to receive...
     248             :  * But it seems useful to report the username and authorization method
     249             :  * in use, and these are items that must be presumed known to an attacker
     250             :  * anyway.
     251             :  * Note that many sorts of failure report additional information in the
     252             :  * postmaster log, which we hope is only readable by good guys.  In
     253             :  * particular, if logdetail isn't NULL, we send that string to the log.
     254             :  */
     255             : static void
     256          32 : auth_failed(Port *port, int status, char *logdetail)
     257             : {
     258             :     const char *errstr;
     259             :     char       *cdetail;
     260          32 :     int         errcode_return = ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION;
     261             : 
     262             :     /*
     263             :      * If we failed due to EOF from client, just quit; there's no point in
     264             :      * trying to send a message to the client, and not much point in logging
     265             :      * the failure in the postmaster log.  (Logging the failure might be
     266             :      * desirable, were it not for the fact that libpq closes the connection
     267             :      * unceremoniously if challenged for a password when it hasn't got one to
     268             :      * send.  We'll get a useless log entry for every psql connection under
     269             :      * password auth, even if it's perfectly successful, if we log STATUS_EOF
     270             :      * events.)
     271             :      */
     272          32 :     if (status == STATUS_EOF)
     273           0 :         proc_exit(0);
     274             : 
     275          32 :     switch (port->hba->auth_method)
     276             :     {
     277             :         case uaReject:
     278             :         case uaImplicitReject:
     279           0 :             errstr = gettext_noop("authentication failed for user \"%s\": host rejected");
     280           0 :             break;
     281             :         case uaTrust:
     282           2 :             errstr = gettext_noop("\"trust\" authentication failed for user \"%s\"");
     283           2 :             break;
     284             :         case uaIdent:
     285           0 :             errstr = gettext_noop("Ident authentication failed for user \"%s\"");
     286           0 :             break;
     287             :         case uaPeer:
     288           0 :             errstr = gettext_noop("Peer authentication failed for user \"%s\"");
     289           0 :             break;
     290             :         case uaPassword:
     291             :         case uaMD5:
     292             :         case uaSCRAM:
     293          10 :             errstr = gettext_noop("password authentication failed for user \"%s\"");
     294             :             /* We use it to indicate if a .pgpass password failed. */
     295          10 :             errcode_return = ERRCODE_INVALID_PASSWORD;
     296          10 :             break;
     297             :         case uaGSS:
     298           0 :             errstr = gettext_noop("GSSAPI authentication failed for user \"%s\"");
     299           0 :             break;
     300             :         case uaSSPI:
     301           0 :             errstr = gettext_noop("SSPI authentication failed for user \"%s\"");
     302           0 :             break;
     303             :         case uaPAM:
     304           0 :             errstr = gettext_noop("PAM authentication failed for user \"%s\"");
     305           0 :             break;
     306             :         case uaBSD:
     307           0 :             errstr = gettext_noop("BSD authentication failed for user \"%s\"");
     308           0 :             break;
     309             :         case uaLDAP:
     310          18 :             errstr = gettext_noop("LDAP authentication failed for user \"%s\"");
     311          18 :             break;
     312             :         case uaCert:
     313           2 :             errstr = gettext_noop("certificate authentication failed for user \"%s\"");
     314           2 :             break;
     315             :         case uaRADIUS:
     316           0 :             errstr = gettext_noop("RADIUS authentication failed for user \"%s\"");
     317           0 :             break;
     318             :         default:
     319           0 :             errstr = gettext_noop("authentication failed for user \"%s\": invalid authentication method");
     320           0 :             break;
     321             :     }
     322             : 
     323          64 :     cdetail = psprintf(_("Connection matched pg_hba.conf line %d: \"%s\""),
     324          64 :                        port->hba->linenumber, port->hba->rawline);
     325          32 :     if (logdetail)
     326           2 :         logdetail = psprintf("%s\n%s", logdetail, cdetail);
     327             :     else
     328          30 :         logdetail = cdetail;
     329             : 
     330          32 :     ereport(FATAL,
     331             :             (errcode(errcode_return),
     332             :              errmsg(errstr, port->user_name),
     333             :              logdetail ? errdetail_log("%s", logdetail) : 0));
     334             : 
     335             :     /* doesn't return */
     336             : }
     337             : 
     338             : 
     339             : /*
     340             :  * Client authentication starts here.  If there is an error, this
     341             :  * function does not return and the backend process is terminated.
     342             :  */
     343             : void
     344        6592 : ClientAuthentication(Port *port)
     345             : {
     346        6592 :     int         status = STATUS_ERROR;
     347        6592 :     char       *logdetail = NULL;
     348             : 
     349             :     /*
     350             :      * Get the authentication method to use for this frontend/database
     351             :      * combination.  Note: we do not parse the file at this point; this has
     352             :      * already been done elsewhere.  hba.c dropped an error message into the
     353             :      * server logfile if parsing the hba config file failed.
     354             :      */
     355        6592 :     hba_getauthmethod(port);
     356             : 
     357        6592 :     CHECK_FOR_INTERRUPTS();
     358             : 
     359             :     /*
     360             :      * This is the first point where we have access to the hba record for the
     361             :      * current connection, so perform any verifications based on the hba
     362             :      * options field that should be done *before* the authentication here.
     363             :      */
     364        6592 :     if (port->hba->clientcert != clientCertOff)
     365             :     {
     366             :         /* If we haven't loaded a root certificate store, fail */
     367          16 :         if (!secure_loaded_verify_locations())
     368           0 :             ereport(FATAL,
     369             :                     (errcode(ERRCODE_CONFIG_FILE_ERROR),
     370             :                      errmsg("client certificates can only be checked if a root certificate store is available")));
     371             : 
     372             :         /*
     373             :          * If we loaded a root certificate store, and if a certificate is
     374             :          * present on the client, then it has been verified against our root
     375             :          * certificate store, and the connection would have been aborted
     376             :          * already if it didn't verify ok.
     377             :          */
     378          16 :         if (!port->peer_cert_valid)
     379           2 :             ereport(FATAL,
     380             :                     (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
     381             :                      errmsg("connection requires a valid client certificate")));
     382             :     }
     383             : 
     384             : #ifdef ENABLE_GSS
     385             :     if (port->gss->enc && port->hba->auth_method != uaReject &&
     386             :         port->hba->auth_method != uaImplicitReject &&
     387             :         port->hba->auth_method != uaTrust &&
     388             :         port->hba->auth_method != uaGSS)
     389             :     {
     390             :         ereport(FATAL, (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
     391             :                         errmsg("GSSAPI encryption can only be used with gss, trust, or reject authentication methods")));
     392             :     }
     393             : #endif
     394             : 
     395             :     /*
     396             :      * Now proceed to do the actual authentication check
     397             :      */
     398        6590 :     switch (port->hba->auth_method)
     399             :     {
     400             :         case uaReject:
     401             : 
     402             :             /*
     403             :              * An explicit "reject" entry in pg_hba.conf.  This report exposes
     404             :              * the fact that there's an explicit reject entry, which is
     405             :              * perhaps not so desirable from a security standpoint; but the
     406             :              * message for an implicit reject could confuse the DBA a lot when
     407             :              * the true situation is a match to an explicit reject.  And we
     408             :              * don't want to change the message for an implicit reject.  As
     409             :              * noted below, the additional information shown here doesn't
     410             :              * expose anything not known to an attacker.
     411             :              */
     412             :             {
     413             :                 char        hostinfo[NI_MAXHOST];
     414             : 
     415           0 :                 pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
     416             :                                    hostinfo, sizeof(hostinfo),
     417             :                                    NULL, 0,
     418             :                                    NI_NUMERICHOST);
     419             : 
     420           0 :                 if (am_walsender)
     421             :                 {
     422             : #ifdef USE_SSL
     423           0 :                     ereport(FATAL,
     424             :                             (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
     425             :                              errmsg("pg_hba.conf rejects replication connection for host \"%s\", user \"%s\", %s",
     426             :                                     hostinfo, port->user_name,
     427             :                                     port->ssl_in_use ? _("SSL on") : _("SSL off"))));
     428             : #else
     429             :                     ereport(FATAL,
     430             :                             (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
     431             :                              errmsg("pg_hba.conf rejects replication connection for host \"%s\", user \"%s\"",
     432             :                                     hostinfo, port->user_name)));
     433             : #endif
     434             :                 }
     435             :                 else
     436             :                 {
     437             : #ifdef USE_SSL
     438           0 :                     ereport(FATAL,
     439             :                             (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
     440             :                              errmsg("pg_hba.conf rejects connection for host \"%s\", user \"%s\", database \"%s\", %s",
     441             :                                     hostinfo, port->user_name,
     442             :                                     port->database_name,
     443             :                                     port->ssl_in_use ? _("SSL on") : _("SSL off"))));
     444             : #else
     445             :                     ereport(FATAL,
     446             :                             (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
     447             :                              errmsg("pg_hba.conf rejects connection for host \"%s\", user \"%s\", database \"%s\"",
     448             :                                     hostinfo, port->user_name,
     449             :                                     port->database_name)));
     450             : #endif
     451             :                 }
     452             :                 break;
     453             :             }
     454             : 
     455             :         case uaImplicitReject:
     456             : 
     457             :             /*
     458             :              * No matching entry, so tell the user we fell through.
     459             :              *
     460             :              * NOTE: the extra info reported here is not a security breach,
     461             :              * because all that info is known at the frontend and must be
     462             :              * assumed known to bad guys.  We're merely helping out the less
     463             :              * clueful good guys.
     464             :              */
     465             :             {
     466             :                 char        hostinfo[NI_MAXHOST];
     467             : 
     468           2 :                 pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
     469             :                                    hostinfo, sizeof(hostinfo),
     470             :                                    NULL, 0,
     471             :                                    NI_NUMERICHOST);
     472             : 
     473             : #define HOSTNAME_LOOKUP_DETAIL(port) \
     474             :                 (port->remote_hostname ? \
     475             :                  (port->remote_hostname_resolv == +1 ? \
     476             :                   errdetail_log("Client IP address resolved to \"%s\", forward lookup matches.", \
     477             :                                 port->remote_hostname) : \
     478             :                   port->remote_hostname_resolv == 0 ? \
     479             :                   errdetail_log("Client IP address resolved to \"%s\", forward lookup not checked.", \
     480             :                                 port->remote_hostname) : \
     481             :                   port->remote_hostname_resolv == -1 ? \
     482             :                   errdetail_log("Client IP address resolved to \"%s\", forward lookup does not match.", \
     483             :                                 port->remote_hostname) : \
     484             :                   port->remote_hostname_resolv == -2 ? \
     485             :                   errdetail_log("Could not translate client host name \"%s\" to IP address: %s.", \
     486             :                                 port->remote_hostname, \
     487             :                                 gai_strerror(port->remote_hostname_errcode)) : \
     488             :                   0) \
     489             :                  : (port->remote_hostname_resolv == -2 ? \
     490             :                     errdetail_log("Could not resolve client IP address to a host name: %s.", \
     491             :                                   gai_strerror(port->remote_hostname_errcode)) : \
     492             :                     0))
     493             : 
     494           2 :                 if (am_walsender)
     495             :                 {
     496             : #ifdef USE_SSL
     497           0 :                     ereport(FATAL,
     498             :                             (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
     499             :                              errmsg("no pg_hba.conf entry for replication connection from host \"%s\", user \"%s\", %s",
     500             :                                     hostinfo, port->user_name,
     501             :                                     port->ssl_in_use ? _("SSL on") : _("SSL off")),
     502             :                              HOSTNAME_LOOKUP_DETAIL(port)));
     503             : #else
     504             :                     ereport(FATAL,
     505             :                             (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
     506             :                              errmsg("no pg_hba.conf entry for replication connection from host \"%s\", user \"%s\"",
     507             :                                     hostinfo, port->user_name),
     508             :                              HOSTNAME_LOOKUP_DETAIL(port)));
     509             : #endif
     510             :                 }
     511             :                 else
     512             :                 {
     513             : #ifdef USE_SSL
     514           2 :                     ereport(FATAL,
     515             :                             (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
     516             :                              errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\", %s",
     517             :                                     hostinfo, port->user_name,
     518             :                                     port->database_name,
     519             :                                     port->ssl_in_use ? _("SSL on") : _("SSL off")),
     520             :                              HOSTNAME_LOOKUP_DETAIL(port)));
     521             : #else
     522             :                     ereport(FATAL,
     523             :                             (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
     524             :                              errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\"",
     525             :                                     hostinfo, port->user_name,
     526             :                                     port->database_name),
     527             :                              HOSTNAME_LOOKUP_DETAIL(port)));
     528             : #endif
     529             :                 }
     530             :                 break;
     531             :             }
     532             : 
     533             :         case uaGSS:
     534             : #ifdef ENABLE_GSS
     535             :             port->gss->auth = true;
     536             :             if (port->gss->enc)
     537             :                 status = pg_GSS_checkauth(port);
     538             :             else
     539             :             {
     540             :                 sendAuthRequest(port, AUTH_REQ_GSS, NULL, 0);
     541             :                 status = pg_GSS_recvauth(port);
     542             :             }
     543             : #else
     544             :             Assert(false);
     545             : #endif
     546           0 :             break;
     547             : 
     548             :         case uaSSPI:
     549             : #ifdef ENABLE_SSPI
     550             :             sendAuthRequest(port, AUTH_REQ_SSPI, NULL, 0);
     551             :             status = pg_SSPI_recvauth(port);
     552             : #else
     553             :             Assert(false);
     554             : #endif
     555           0 :             break;
     556             : 
     557             :         case uaPeer:
     558             : #ifdef HAVE_UNIX_SOCKETS
     559           0 :             status = auth_peer(port);
     560             : #else
     561             :             Assert(false);
     562             : #endif
     563           0 :             break;
     564             : 
     565             :         case uaIdent:
     566           0 :             status = ident_inet(port);
     567           0 :             break;
     568             : 
     569             :         case uaMD5:
     570             :         case uaSCRAM:
     571          32 :             status = CheckPWChallengeAuth(port, &logdetail);
     572          32 :             break;
     573             : 
     574             :         case uaPassword:
     575           4 :             status = CheckPasswordAuth(port, &logdetail);
     576           4 :             break;
     577             : 
     578             :         case uaPAM:
     579             : #ifdef USE_PAM
     580           0 :             status = CheckPAMAuth(port, port->user_name, "");
     581             : #else
     582             :             Assert(false);
     583             : #endif                          /* USE_PAM */
     584           0 :             break;
     585             : 
     586             :         case uaBSD:
     587             : #ifdef USE_BSD_AUTH
     588             :             status = CheckBSDAuth(port, port->user_name);
     589             : #else
     590             :             Assert(false);
     591             : #endif                          /* USE_BSD_AUTH */
     592           0 :             break;
     593             : 
     594             :         case uaLDAP:
     595             : #ifdef USE_LDAP
     596          42 :             status = CheckLDAPAuth(port);
     597             : #else
     598             :             Assert(false);
     599             : #endif
     600          42 :             break;
     601             :         case uaRADIUS:
     602           0 :             status = CheckRADIUSAuth(port);
     603           0 :             break;
     604             :         case uaCert:
     605             :             /* uaCert will be treated as if clientcert=verify-full (uaTrust) */
     606             :         case uaTrust:
     607        6510 :             status = STATUS_OK;
     608        6510 :             break;
     609             :     }
     610             : 
     611        6588 :     if ((status == STATUS_OK && port->hba->clientcert == clientCertFull)
     612        6584 :         || port->hba->auth_method == uaCert)
     613             :     {
     614             :         /*
     615             :          * Make sure we only check the certificate if we use the cert method
     616             :          * or verify-full option.
     617             :          */
     618             : #ifdef USE_SSL
     619          12 :         status = CheckCertAuth(port);
     620             : #else
     621             :         Assert(false);
     622             : #endif
     623             :     }
     624             : 
     625        6588 :     if (ClientAuthentication_hook)
     626           0 :         (*ClientAuthentication_hook) (port, status);
     627             : 
     628        6588 :     if (status == STATUS_OK)
     629        6556 :         sendAuthRequest(port, AUTH_REQ_OK, NULL, 0);
     630             :     else
     631          32 :         auth_failed(port, status, logdetail);
     632        6556 : }
     633             : 
     634             : 
     635             : /*
     636             :  * Send an authentication request packet to the frontend.
     637             :  */
     638             : static void
     639        6688 : sendAuthRequest(Port *port, AuthRequest areq, const char *extradata, int extralen)
     640             : {
     641             :     StringInfoData buf;
     642             : 
     643        6688 :     CHECK_FOR_INTERRUPTS();
     644             : 
     645        6688 :     pq_beginmessage(&buf, 'R');
     646        6688 :     pq_sendint32(&buf, (int32) areq);
     647        6688 :     if (extralen > 0)
     648          86 :         pq_sendbytes(&buf, extradata, extralen);
     649             : 
     650        6688 :     pq_endmessage(&buf);
     651             : 
     652             :     /*
     653             :      * Flush message so client will see it, except for AUTH_REQ_OK and
     654             :      * AUTH_REQ_SASL_FIN, which need not be sent until we are ready for
     655             :      * queries.
     656             :      */
     657        6688 :     if (areq != AUTH_REQ_OK && areq != AUTH_REQ_SASL_FIN)
     658         110 :         pq_flush();
     659             : 
     660        6688 :     CHECK_FOR_INTERRUPTS();
     661        6688 : }
     662             : 
     663             : /*
     664             :  * Collect password response packet from frontend.
     665             :  *
     666             :  * Returns NULL if couldn't get password, else palloc'd string.
     667             :  */
     668             : static char *
     669          46 : recv_password_packet(Port *port)
     670             : {
     671             :     StringInfoData buf;
     672             : 
     673          46 :     pq_startmsgread();
     674          46 :     if (PG_PROTOCOL_MAJOR(port->proto) >= 3)
     675             :     {
     676             :         /* Expect 'p' message type */
     677             :         int         mtype;
     678             : 
     679          46 :         mtype = pq_getbyte();
     680          46 :         if (mtype != 'p')
     681             :         {
     682             :             /*
     683             :              * If the client just disconnects without offering a password,
     684             :              * don't make a log entry.  This is legal per protocol spec and in
     685             :              * fact commonly done by psql, so complaining just clutters the
     686             :              * log.
     687             :              */
     688           0 :             if (mtype != EOF)
     689           0 :                 ereport(ERROR,
     690             :                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
     691             :                          errmsg("expected password response, got message type %d",
     692             :                                 mtype)));
     693           0 :             return NULL;        /* EOF or bad message type */
     694             :         }
     695             :     }
     696             :     else
     697             :     {
     698             :         /* For pre-3.0 clients, avoid log entry if they just disconnect */
     699           0 :         if (pq_peekbyte() == EOF)
     700           0 :             return NULL;        /* EOF */
     701             :     }
     702             : 
     703          46 :     initStringInfo(&buf);
     704          46 :     if (pq_getmessage(&buf, 1000))  /* receive password */
     705             :     {
     706             :         /* EOF - pq_getmessage already logged a suitable message */
     707           0 :         pfree(buf.data);
     708           0 :         return NULL;
     709             :     }
     710             : 
     711             :     /*
     712             :      * Apply sanity check: password packet length should agree with length of
     713             :      * contained string.  Note it is safe to use strlen here because
     714             :      * StringInfo is guaranteed to have an appended '\0'.
     715             :      */
     716          46 :     if (strlen(buf.data) + 1 != buf.len)
     717           0 :         ereport(ERROR,
     718             :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
     719             :                  errmsg("invalid password packet size")));
     720             : 
     721             :     /*
     722             :      * Don't allow an empty password. Libpq treats an empty password the same
     723             :      * as no password at all, and won't even try to authenticate. But other
     724             :      * clients might, so allowing it would be confusing.
     725             :      *
     726             :      * Note that this only catches an empty password sent by the client in
     727             :      * plaintext. There's also a check in CREATE/ALTER USER that prevents an
     728             :      * empty string from being stored as a user's password in the first place.
     729             :      * We rely on that for MD5 and SCRAM authentication, but we still need
     730             :      * this check here, to prevent an empty password from being used with
     731             :      * authentication methods that check the password against an external
     732             :      * system, like PAM, LDAP and RADIUS.
     733             :      */
     734          46 :     if (buf.len == 1)
     735           0 :         ereport(ERROR,
     736             :                 (errcode(ERRCODE_INVALID_PASSWORD),
     737             :                  errmsg("empty password returned by client")));
     738             : 
     739             :     /* Do not echo password to logs, for security. */
     740          46 :     elog(DEBUG5, "received password packet");
     741             : 
     742             :     /*
     743             :      * Return the received string.  Note we do not attempt to do any
     744             :      * character-set conversion on it; since we don't yet know the client's
     745             :      * encoding, there wouldn't be much point.
     746             :      */
     747          46 :     return buf.data;
     748             : }
     749             : 
     750             : 
     751             : /*----------------------------------------------------------------
     752             :  * Password-based authentication mechanisms
     753             :  *----------------------------------------------------------------
     754             :  */
     755             : 
     756             : /*
     757             :  * Plaintext password authentication.
     758             :  */
     759             : static int
     760           4 : CheckPasswordAuth(Port *port, char **logdetail)
     761             : {
     762             :     char       *passwd;
     763             :     int         result;
     764             :     char       *shadow_pass;
     765             : 
     766           4 :     sendAuthRequest(port, AUTH_REQ_PASSWORD, NULL, 0);
     767             : 
     768           4 :     passwd = recv_password_packet(port);
     769           4 :     if (passwd == NULL)
     770           0 :         return STATUS_EOF;      /* client wouldn't send password */
     771             : 
     772           4 :     shadow_pass = get_role_password(port->user_name, logdetail);
     773           4 :     if (shadow_pass)
     774             :     {
     775           4 :         result = plain_crypt_verify(port->user_name, shadow_pass, passwd,
     776             :                                     logdetail);
     777             :     }
     778             :     else
     779           0 :         result = STATUS_ERROR;
     780             : 
     781           4 :     if (shadow_pass)
     782           4 :         pfree(shadow_pass);
     783           4 :     pfree(passwd);
     784             : 
     785           4 :     return result;
     786             : }
     787             : 
     788             : /*
     789             :  * MD5 and SCRAM authentication.
     790             :  */
     791             : static int
     792          32 : CheckPWChallengeAuth(Port *port, char **logdetail)
     793             : {
     794             :     int         auth_result;
     795             :     char       *shadow_pass;
     796             :     PasswordType pwtype;
     797             : 
     798             :     Assert(port->hba->auth_method == uaSCRAM ||
     799             :            port->hba->auth_method == uaMD5);
     800             : 
     801             :     /* First look up the user's password. */
     802          32 :     shadow_pass = get_role_password(port->user_name, logdetail);
     803             : 
     804             :     /*
     805             :      * If the user does not exist, or has no password or it's expired, we
     806             :      * still go through the motions of authentication, to avoid revealing to
     807             :      * the client that the user didn't exist.  If 'md5' is allowed, we choose
     808             :      * whether to use 'md5' or 'scram-sha-256' authentication based on current
     809             :      * password_encryption setting.  The idea is that most genuine users
     810             :      * probably have a password of that type, and if we pretend that this user
     811             :      * had a password of that type, too, it "blends in" best.
     812             :      */
     813          32 :     if (!shadow_pass)
     814           0 :         pwtype = Password_encryption;
     815             :     else
     816          32 :         pwtype = get_password_type(shadow_pass);
     817             : 
     818             :     /*
     819             :      * If 'md5' authentication is allowed, decide whether to perform 'md5' or
     820             :      * 'scram-sha-256' authentication based on the type of password the user
     821             :      * has.  If it's an MD5 hash, we must do MD5 authentication, and if it's a
     822             :      * SCRAM verifier, we must do SCRAM authentication.
     823             :      *
     824             :      * If MD5 authentication is not allowed, always use SCRAM.  If the user
     825             :      * had an MD5 password, CheckSCRAMAuth() will fail.
     826             :      */
     827          32 :     if (port->hba->auth_method == uaMD5 && pwtype == PASSWORD_TYPE_MD5)
     828           0 :         auth_result = CheckMD5Auth(port, shadow_pass, logdetail);
     829             :     else
     830          32 :         auth_result = CheckSCRAMAuth(port, shadow_pass, logdetail);
     831             : 
     832          32 :     if (shadow_pass)
     833          32 :         pfree(shadow_pass);
     834             : 
     835             :     /*
     836             :      * If get_role_password() returned error, return error, even if the
     837             :      * authentication succeeded.
     838             :      */
     839          32 :     if (!shadow_pass)
     840             :     {
     841             :         Assert(auth_result != STATUS_OK);
     842           0 :         return STATUS_ERROR;
     843             :     }
     844          32 :     return auth_result;
     845             : }
     846             : 
     847             : static int
     848           0 : CheckMD5Auth(Port *port, char *shadow_pass, char **logdetail)
     849             : {
     850             :     char        md5Salt[4];     /* Password salt */
     851             :     char       *passwd;
     852             :     int         result;
     853             : 
     854           0 :     if (Db_user_namespace)
     855           0 :         ereport(FATAL,
     856             :                 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
     857             :                  errmsg("MD5 authentication is not supported when \"db_user_namespace\" is enabled")));
     858             : 
     859             :     /* include the salt to use for computing the response */
     860           0 :     if (!pg_strong_random(md5Salt, 4))
     861             :     {
     862           0 :         ereport(LOG,
     863             :                 (errmsg("could not generate random MD5 salt")));
     864           0 :         return STATUS_ERROR;
     865             :     }
     866             : 
     867           0 :     sendAuthRequest(port, AUTH_REQ_MD5, md5Salt, 4);
     868             : 
     869           0 :     passwd = recv_password_packet(port);
     870           0 :     if (passwd == NULL)
     871           0 :         return STATUS_EOF;      /* client wouldn't send password */
     872             : 
     873           0 :     if (shadow_pass)
     874           0 :         result = md5_crypt_verify(port->user_name, shadow_pass, passwd,
     875             :                                   md5Salt, 4, logdetail);
     876             :     else
     877           0 :         result = STATUS_ERROR;
     878             : 
     879           0 :     pfree(passwd);
     880             : 
     881           0 :     return result;
     882             : }
     883             : 
     884             : static int
     885          32 : CheckSCRAMAuth(Port *port, char *shadow_pass, char **logdetail)
     886             : {
     887             :     StringInfoData sasl_mechs;
     888             :     int         mtype;
     889             :     StringInfoData buf;
     890          32 :     void       *scram_opaq = NULL;
     891          32 :     char       *output = NULL;
     892          32 :     int         outputlen = 0;
     893             :     const char *input;
     894             :     int         inputlen;
     895             :     int         result;
     896             :     bool        initial;
     897             : 
     898             :     /*
     899             :      * SASL auth is not supported for protocol versions before 3, because it
     900             :      * relies on the overall message length word to determine the SASL payload
     901             :      * size in AuthenticationSASLContinue and PasswordMessage messages.  (We
     902             :      * used to have a hard rule that protocol messages must be parsable
     903             :      * without relying on the length word, but we hardly care about older
     904             :      * protocol version anymore.)
     905             :      */
     906          32 :     if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
     907           0 :         ereport(FATAL,
     908             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     909             :                  errmsg("SASL authentication is not supported in protocol version 2")));
     910             : 
     911             :     /*
     912             :      * Send the SASL authentication request to user.  It includes the list of
     913             :      * authentication mechanisms that are supported.
     914             :      */
     915          32 :     initStringInfo(&sasl_mechs);
     916             : 
     917          32 :     pg_be_scram_get_mechanisms(port, &sasl_mechs);
     918             :     /* Put another '\0' to mark that list is finished. */
     919          32 :     appendStringInfoChar(&sasl_mechs, '\0');
     920             : 
     921          32 :     sendAuthRequest(port, AUTH_REQ_SASL, sasl_mechs.data, sasl_mechs.len);
     922          32 :     pfree(sasl_mechs.data);
     923             : 
     924             :     /*
     925             :      * Loop through SASL message exchange.  This exchange can consist of
     926             :      * multiple messages sent in both directions.  First message is always
     927             :      * from the client.  All messages from client to server are password
     928             :      * packets (type 'p').
     929             :      */
     930          32 :     initial = true;
     931             :     do
     932             :     {
     933          64 :         pq_startmsgread();
     934          64 :         mtype = pq_getbyte();
     935          64 :         if (mtype != 'p')
     936             :         {
     937             :             /* Only log error if client didn't disconnect. */
     938           0 :             if (mtype != EOF)
     939             :             {
     940           0 :                 ereport(ERROR,
     941             :                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
     942             :                          errmsg("expected SASL response, got message type %d",
     943             :                                 mtype)));
     944             :             }
     945             :             else
     946           0 :                 return STATUS_EOF;
     947             :         }
     948             : 
     949             :         /* Get the actual SASL message */
     950          64 :         initStringInfo(&buf);
     951          64 :         if (pq_getmessage(&buf, PG_MAX_SASL_MESSAGE_LENGTH))
     952             :         {
     953             :             /* EOF - pq_getmessage already logged error */
     954           0 :             pfree(buf.data);
     955           0 :             return STATUS_ERROR;
     956             :         }
     957             : 
     958          64 :         elog(DEBUG4, "Processing received SASL response of length %d", buf.len);
     959             : 
     960             :         /*
     961             :          * The first SASLInitialResponse message is different from the others.
     962             :          * It indicates which SASL mechanism the client selected, and contains
     963             :          * an optional Initial Client Response payload.  The subsequent
     964             :          * SASLResponse messages contain just the SASL payload.
     965             :          */
     966          64 :         if (initial)
     967             :         {
     968             :             const char *selected_mech;
     969             : 
     970          32 :             selected_mech = pq_getmsgrawstring(&buf);
     971             : 
     972             :             /*
     973             :              * Initialize the status tracker for message exchanges.
     974             :              *
     975             :              * If the user doesn't exist, or doesn't have a valid password, or
     976             :              * it's expired, we still go through the motions of SASL
     977             :              * authentication, but tell the authentication method that the
     978             :              * authentication is "doomed". That is, it's going to fail, no
     979             :              * matter what.
     980             :              *
     981             :              * This is because we don't want to reveal to an attacker what
     982             :              * usernames are valid, nor which users have a valid password.
     983             :              */
     984          32 :             scram_opaq = pg_be_scram_init(port, selected_mech, shadow_pass);
     985             : 
     986          32 :             inputlen = pq_getmsgint(&buf, 4);
     987          32 :             if (inputlen == -1)
     988           0 :                 input = NULL;
     989             :             else
     990          32 :                 input = pq_getmsgbytes(&buf, inputlen);
     991             : 
     992          32 :             initial = false;
     993             :         }
     994             :         else
     995             :         {
     996          32 :             inputlen = buf.len;
     997          32 :             input = pq_getmsgbytes(&buf, buf.len);
     998             :         }
     999          64 :         pq_getmsgend(&buf);
    1000             : 
    1001             :         /*
    1002             :          * The StringInfo guarantees that there's a \0 byte after the
    1003             :          * response.
    1004             :          */
    1005             :         Assert(input == NULL || input[inputlen] == '\0');
    1006             : 
    1007             :         /*
    1008             :          * we pass 'logdetail' as NULL when doing a mock authentication,
    1009             :          * because we should already have a better error message in that case
    1010             :          */
    1011          64 :         result = pg_be_scram_exchange(scram_opaq, input, inputlen,
    1012             :                                       &output, &outputlen,
    1013             :                                       logdetail);
    1014             : 
    1015             :         /* input buffer no longer used */
    1016          64 :         pfree(buf.data);
    1017             : 
    1018          64 :         if (output)
    1019             :         {
    1020             :             /*
    1021             :              * Negotiation generated data to be sent to the client.
    1022             :              */
    1023          54 :             elog(DEBUG4, "sending SASL challenge of length %u", outputlen);
    1024             : 
    1025          54 :             if (result == SASL_EXCHANGE_SUCCESS)
    1026          22 :                 sendAuthRequest(port, AUTH_REQ_SASL_FIN, output, outputlen);
    1027             :             else
    1028          32 :                 sendAuthRequest(port, AUTH_REQ_SASL_CONT, output, outputlen);
    1029             : 
    1030          54 :             pfree(output);
    1031             :         }
    1032          64 :     } while (result == SASL_EXCHANGE_CONTINUE);
    1033             : 
    1034             :     /* Oops, Something bad happened */
    1035          32 :     if (result != SASL_EXCHANGE_SUCCESS)
    1036             :     {
    1037          10 :         return STATUS_ERROR;
    1038             :     }
    1039             : 
    1040          22 :     return STATUS_OK;
    1041             : }
    1042             : 
    1043             : 
    1044             : /*----------------------------------------------------------------
    1045             :  * GSSAPI authentication system
    1046             :  *----------------------------------------------------------------
    1047             :  */
    1048             : #ifdef ENABLE_GSS
    1049             : static int
    1050             : pg_GSS_recvauth(Port *port)
    1051             : {
    1052             :     OM_uint32   maj_stat,
    1053             :                 min_stat,
    1054             :                 lmin_s,
    1055             :                 gflags;
    1056             :     int         mtype;
    1057             :     StringInfoData buf;
    1058             :     gss_buffer_desc gbuf;
    1059             : 
    1060             :     /*
    1061             :      * GSS auth is not supported for protocol versions before 3, because it
    1062             :      * relies on the overall message length word to determine the GSS payload
    1063             :      * size in AuthenticationGSSContinue and PasswordMessage messages. (This
    1064             :      * is, in fact, a design error in our GSS support, because protocol
    1065             :      * messages are supposed to be parsable without relying on the length
    1066             :      * word; but it's not worth changing it now.)
    1067             :      */
    1068             :     if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
    1069             :         ereport(FATAL,
    1070             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1071             :                  errmsg("GSSAPI is not supported in protocol version 2")));
    1072             : 
    1073             :     if (pg_krb_server_keyfile && strlen(pg_krb_server_keyfile) > 0)
    1074             :     {
    1075             :         /*
    1076             :          * Set default Kerberos keytab file for the Krb5 mechanism.
    1077             :          *
    1078             :          * setenv("KRB5_KTNAME", pg_krb_server_keyfile, 0); except setenv()
    1079             :          * not always available.
    1080             :          */
    1081             :         if (getenv("KRB5_KTNAME") == NULL)
    1082             :         {
    1083             :             size_t      kt_len = strlen(pg_krb_server_keyfile) + 14;
    1084             :             char       *kt_path = malloc(kt_len);
    1085             : 
    1086             :             if (!kt_path ||
    1087             :                 snprintf(kt_path, kt_len, "KRB5_KTNAME=%s",
    1088             :                          pg_krb_server_keyfile) != kt_len - 2 ||
    1089             :                 putenv(kt_path) != 0)
    1090             :             {
    1091             :                 ereport(LOG,
    1092             :                         (errcode(ERRCODE_OUT_OF_MEMORY),
    1093             :                          errmsg("out of memory")));
    1094             :                 return STATUS_ERROR;
    1095             :             }
    1096             :         }
    1097             :     }
    1098             : 
    1099             :     /*
    1100             :      * We accept any service principal that's present in our keytab. This
    1101             :      * increases interoperability between kerberos implementations that see
    1102             :      * for example case sensitivity differently, while not really opening up
    1103             :      * any vector of attack.
    1104             :      */
    1105             :     port->gss->cred = GSS_C_NO_CREDENTIAL;
    1106             : 
    1107             :     /*
    1108             :      * Initialize sequence with an empty context
    1109             :      */
    1110             :     port->gss->ctx = GSS_C_NO_CONTEXT;
    1111             : 
    1112             :     /*
    1113             :      * Loop through GSSAPI message exchange. This exchange can consist of
    1114             :      * multiple messages sent in both directions. First message is always from
    1115             :      * the client. All messages from client to server are password packets
    1116             :      * (type 'p').
    1117             :      */
    1118             :     do
    1119             :     {
    1120             :         pq_startmsgread();
    1121             : 
    1122             :         CHECK_FOR_INTERRUPTS();
    1123             : 
    1124             :         mtype = pq_getbyte();
    1125             :         if (mtype != 'p')
    1126             :         {
    1127             :             /* Only log error if client didn't disconnect. */
    1128             :             if (mtype != EOF)
    1129             :                 ereport(ERROR,
    1130             :                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
    1131             :                          errmsg("expected GSS response, got message type %d",
    1132             :                                 mtype)));
    1133             :             return STATUS_ERROR;
    1134             :         }
    1135             : 
    1136             :         /* Get the actual GSS token */
    1137             :         initStringInfo(&buf);
    1138             :         if (pq_getmessage(&buf, PG_MAX_AUTH_TOKEN_LENGTH))
    1139             :         {
    1140             :             /* EOF - pq_getmessage already logged error */
    1141             :             pfree(buf.data);
    1142             :             return STATUS_ERROR;
    1143             :         }
    1144             : 
    1145             :         /* Map to GSSAPI style buffer */
    1146             :         gbuf.length = buf.len;
    1147             :         gbuf.value = buf.data;
    1148             : 
    1149             :         elog(DEBUG4, "Processing received GSS token of length %u",
    1150             :              (unsigned int) gbuf.length);
    1151             : 
    1152             :         maj_stat = gss_accept_sec_context(
    1153             :                                           &min_stat,
    1154             :                                           &port->gss->ctx,
    1155             :                                           port->gss->cred,
    1156             :                                           &gbuf,
    1157             :                                           GSS_C_NO_CHANNEL_BINDINGS,
    1158             :                                           &port->gss->name,
    1159             :                                           NULL,
    1160             :                                           &port->gss->outbuf,
    1161             :                                           &gflags,
    1162             :                                           NULL,
    1163             :                                           NULL);
    1164             : 
    1165             :         /* gbuf no longer used */
    1166             :         pfree(buf.data);
    1167             : 
    1168             :         elog(DEBUG5, "gss_accept_sec_context major: %d, "
    1169             :              "minor: %d, outlen: %u, outflags: %x",
    1170             :              maj_stat, min_stat,
    1171             :              (unsigned int) port->gss->outbuf.length, gflags);
    1172             : 
    1173             :         CHECK_FOR_INTERRUPTS();
    1174             : 
    1175             :         if (port->gss->outbuf.length != 0)
    1176             :         {
    1177             :             /*
    1178             :              * Negotiation generated data to be sent to the client.
    1179             :              */
    1180             :             elog(DEBUG4, "sending GSS response token of length %u",
    1181             :                  (unsigned int) port->gss->outbuf.length);
    1182             : 
    1183             :             sendAuthRequest(port, AUTH_REQ_GSS_CONT,
    1184             :                             port->gss->outbuf.value, port->gss->outbuf.length);
    1185             : 
    1186             :             gss_release_buffer(&lmin_s, &port->gss->outbuf);
    1187             :         }
    1188             : 
    1189             :         if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
    1190             :         {
    1191             :             gss_delete_sec_context(&lmin_s, &port->gss->ctx, GSS_C_NO_BUFFER);
    1192             :             pg_GSS_error(ERROR,
    1193             :                          _("accepting GSS security context failed"),
    1194             :                          maj_stat, min_stat);
    1195             :         }
    1196             : 
    1197             :         if (maj_stat == GSS_S_CONTINUE_NEEDED)
    1198             :             elog(DEBUG4, "GSS continue needed");
    1199             : 
    1200             :     } while (maj_stat == GSS_S_CONTINUE_NEEDED);
    1201             : 
    1202             :     if (port->gss->cred != GSS_C_NO_CREDENTIAL)
    1203             :     {
    1204             :         /*
    1205             :          * Release service principal credentials
    1206             :          */
    1207             :         gss_release_cred(&min_stat, &port->gss->cred);
    1208             :     }
    1209             :     return pg_GSS_checkauth(port);
    1210             : }
    1211             : 
    1212             : /*
    1213             :  * Check whether the GSSAPI-authenticated user is allowed to connect as the
    1214             :  * claimed username.
    1215             :  */
    1216             : static int
    1217             : pg_GSS_checkauth(Port *port)
    1218             : {
    1219             :     int         ret;
    1220             :     OM_uint32   maj_stat,
    1221             :                 min_stat,
    1222             :                 lmin_s;
    1223             :     gss_buffer_desc gbuf;
    1224             : 
    1225             :     /*
    1226             :      * Get the name of the user that authenticated, and compare it to the pg
    1227             :      * username that was specified for the connection.
    1228             :      */
    1229             :     maj_stat = gss_display_name(&min_stat, port->gss->name, &gbuf, NULL);
    1230             :     if (maj_stat != GSS_S_COMPLETE)
    1231             :         pg_GSS_error(ERROR,
    1232             :                      _("retrieving GSS user name failed"),
    1233             :                      maj_stat, min_stat);
    1234             : 
    1235             :     /*
    1236             :      * Copy the original name of the authenticated principal into our backend
    1237             :      * memory for display later.
    1238             :      */
    1239             :     port->gss->princ = MemoryContextStrdup(TopMemoryContext, gbuf.value);
    1240             : 
    1241             :     /*
    1242             :      * Split the username at the realm separator
    1243             :      */
    1244             :     if (strchr(gbuf.value, '@'))
    1245             :     {
    1246             :         char       *cp = strchr(gbuf.value, '@');
    1247             : 
    1248             :         /*
    1249             :          * If we are not going to include the realm in the username that is
    1250             :          * passed to the ident map, destructively modify it here to remove the
    1251             :          * realm. Then advance past the separator to check the realm.
    1252             :          */
    1253             :         if (!port->hba->include_realm)
    1254             :             *cp = '\0';
    1255             :         cp++;
    1256             : 
    1257             :         if (port->hba->krb_realm != NULL && strlen(port->hba->krb_realm))
    1258             :         {
    1259             :             /*
    1260             :              * Match the realm part of the name first
    1261             :              */
    1262             :             if (pg_krb_caseins_users)
    1263             :                 ret = pg_strcasecmp(port->hba->krb_realm, cp);
    1264             :             else
    1265             :                 ret = strcmp(port->hba->krb_realm, cp);
    1266             : 
    1267             :             if (ret)
    1268             :             {
    1269             :                 /* GSS realm does not match */
    1270             :                 elog(DEBUG2,
    1271             :                      "GSSAPI realm (%s) and configured realm (%s) don't match",
    1272             :                      cp, port->hba->krb_realm);
    1273             :                 gss_release_buffer(&lmin_s, &gbuf);
    1274             :                 return STATUS_ERROR;
    1275             :             }
    1276             :         }
    1277             :     }
    1278             :     else if (port->hba->krb_realm && strlen(port->hba->krb_realm))
    1279             :     {
    1280             :         elog(DEBUG2,
    1281             :              "GSSAPI did not return realm but realm matching was requested");
    1282             : 
    1283             :         gss_release_buffer(&lmin_s, &gbuf);
    1284             :         return STATUS_ERROR;
    1285             :     }
    1286             : 
    1287             :     ret = check_usermap(port->hba->usermap, port->user_name, gbuf.value,
    1288             :                         pg_krb_caseins_users);
    1289             : 
    1290             :     gss_release_buffer(&lmin_s, &gbuf);
    1291             : 
    1292             :     return ret;
    1293             : }
    1294             : #endif                          /* ENABLE_GSS */
    1295             : 
    1296             : 
    1297             : /*----------------------------------------------------------------
    1298             :  * SSPI authentication system
    1299             :  *----------------------------------------------------------------
    1300             :  */
    1301             : #ifdef ENABLE_SSPI
    1302             : 
    1303             : /*
    1304             :  * Generate an error for SSPI authentication.  The caller should apply
    1305             :  * _() to errmsg to make it translatable.
    1306             :  */
    1307             : static void
    1308             : pg_SSPI_error(int severity, const char *errmsg, SECURITY_STATUS r)
    1309             : {
    1310             :     char        sysmsg[256];
    1311             : 
    1312             :     if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
    1313             :                       FORMAT_MESSAGE_FROM_SYSTEM,
    1314             :                       NULL, r, 0,
    1315             :                       sysmsg, sizeof(sysmsg), NULL) == 0)
    1316             :         ereport(severity,
    1317             :                 (errmsg_internal("%s", errmsg),
    1318             :                  errdetail_internal("SSPI error %x", (unsigned int) r)));
    1319             :     else
    1320             :         ereport(severity,
    1321             :                 (errmsg_internal("%s", errmsg),
    1322             :                  errdetail_internal("%s (%x)", sysmsg, (unsigned int) r)));
    1323             : }
    1324             : 
    1325             : static int
    1326             : pg_SSPI_recvauth(Port *port)
    1327             : {
    1328             :     int         mtype;
    1329             :     StringInfoData buf;
    1330             :     SECURITY_STATUS r;
    1331             :     CredHandle  sspicred;
    1332             :     CtxtHandle *sspictx = NULL,
    1333             :                 newctx;
    1334             :     TimeStamp   expiry;
    1335             :     ULONG       contextattr;
    1336             :     SecBufferDesc inbuf;
    1337             :     SecBufferDesc outbuf;
    1338             :     SecBuffer   OutBuffers[1];
    1339             :     SecBuffer   InBuffers[1];
    1340             :     HANDLE      token;
    1341             :     TOKEN_USER *tokenuser;
    1342             :     DWORD       retlen;
    1343             :     char        accountname[MAXPGPATH];
    1344             :     char        domainname[MAXPGPATH];
    1345             :     DWORD       accountnamesize = sizeof(accountname);
    1346             :     DWORD       domainnamesize = sizeof(domainname);
    1347             :     SID_NAME_USE accountnameuse;
    1348             :     HMODULE     secur32;
    1349             : 
    1350             :     QUERY_SECURITY_CONTEXT_TOKEN_FN _QuerySecurityContextToken;
    1351             : 
    1352             :     /*
    1353             :      * SSPI auth is not supported for protocol versions before 3, because it
    1354             :      * relies on the overall message length word to determine the SSPI payload
    1355             :      * size in AuthenticationGSSContinue and PasswordMessage messages. (This
    1356             :      * is, in fact, a design error in our SSPI support, because protocol
    1357             :      * messages are supposed to be parsable without relying on the length
    1358             :      * word; but it's not worth changing it now.)
    1359             :      */
    1360             :     if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
    1361             :         ereport(FATAL,
    1362             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1363             :                  errmsg("SSPI is not supported in protocol version 2")));
    1364             : 
    1365             :     /*
    1366             :      * Acquire a handle to the server credentials.
    1367             :      */
    1368             :     r = AcquireCredentialsHandle(NULL,
    1369             :                                  "negotiate",
    1370             :                                  SECPKG_CRED_INBOUND,
    1371             :                                  NULL,
    1372             :                                  NULL,
    1373             :                                  NULL,
    1374             :                                  NULL,
    1375             :                                  &sspicred,
    1376             :                                  &expiry);
    1377             :     if (r != SEC_E_OK)
    1378             :         pg_SSPI_error(ERROR, _("could not acquire SSPI credentials"), r);
    1379             : 
    1380             :     /*
    1381             :      * Loop through SSPI message exchange. This exchange can consist of
    1382             :      * multiple messages sent in both directions. First message is always from
    1383             :      * the client. All messages from client to server are password packets
    1384             :      * (type 'p').
    1385             :      */
    1386             :     do
    1387             :     {
    1388             :         pq_startmsgread();
    1389             :         mtype = pq_getbyte();
    1390             :         if (mtype != 'p')
    1391             :         {
    1392             :             /* Only log error if client didn't disconnect. */
    1393             :             if (mtype != EOF)
    1394             :                 ereport(ERROR,
    1395             :                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
    1396             :                          errmsg("expected SSPI response, got message type %d",
    1397             :                                 mtype)));
    1398             :             return STATUS_ERROR;
    1399             :         }
    1400             : 
    1401             :         /* Get the actual SSPI token */
    1402             :         initStringInfo(&buf);
    1403             :         if (pq_getmessage(&buf, PG_MAX_AUTH_TOKEN_LENGTH))
    1404             :         {
    1405             :             /* EOF - pq_getmessage already logged error */
    1406             :             pfree(buf.data);
    1407             :             return STATUS_ERROR;
    1408             :         }
    1409             : 
    1410             :         /* Map to SSPI style buffer */
    1411             :         inbuf.ulVersion = SECBUFFER_VERSION;
    1412             :         inbuf.cBuffers = 1;
    1413             :         inbuf.pBuffers = InBuffers;
    1414             :         InBuffers[0].pvBuffer = buf.data;
    1415             :         InBuffers[0].cbBuffer = buf.len;
    1416             :         InBuffers[0].BufferType = SECBUFFER_TOKEN;
    1417             : 
    1418             :         /* Prepare output buffer */
    1419             :         OutBuffers[0].pvBuffer = NULL;
    1420             :         OutBuffers[0].BufferType = SECBUFFER_TOKEN;
    1421             :         OutBuffers[0].cbBuffer = 0;
    1422             :         outbuf.cBuffers = 1;
    1423             :         outbuf.pBuffers = OutBuffers;
    1424             :         outbuf.ulVersion = SECBUFFER_VERSION;
    1425             : 
    1426             : 
    1427             :         elog(DEBUG4, "Processing received SSPI token of length %u",
    1428             :              (unsigned int) buf.len);
    1429             : 
    1430             :         r = AcceptSecurityContext(&sspicred,
    1431             :                                   sspictx,
    1432             :                                   &inbuf,
    1433             :                                   ASC_REQ_ALLOCATE_MEMORY,
    1434             :                                   SECURITY_NETWORK_DREP,
    1435             :                                   &newctx,
    1436             :                                   &outbuf,
    1437             :                                   &contextattr,
    1438             :                                   NULL);
    1439             : 
    1440             :         /* input buffer no longer used */
    1441             :         pfree(buf.data);
    1442             : 
    1443             :         if (outbuf.cBuffers > 0 && outbuf.pBuffers[0].cbBuffer > 0)
    1444             :         {
    1445             :             /*
    1446             :              * Negotiation generated data to be sent to the client.
    1447             :              */
    1448             :             elog(DEBUG4, "sending SSPI response token of length %u",
    1449             :                  (unsigned int) outbuf.pBuffers[0].cbBuffer);
    1450             : 
    1451             :             port->gss->outbuf.length = outbuf.pBuffers[0].cbBuffer;
    1452             :             port->gss->outbuf.value = outbuf.pBuffers[0].pvBuffer;
    1453             : 
    1454             :             sendAuthRequest(port, AUTH_REQ_GSS_CONT,
    1455             :                             port->gss->outbuf.value, port->gss->outbuf.length);
    1456             : 
    1457             :             FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
    1458             :         }
    1459             : 
    1460             :         if (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)
    1461             :         {
    1462             :             if (sspictx != NULL)
    1463             :             {
    1464             :                 DeleteSecurityContext(sspictx);
    1465             :                 free(sspictx);
    1466             :             }
    1467             :             FreeCredentialsHandle(&sspicred);
    1468             :             pg_SSPI_error(ERROR,
    1469             :                           _("could not accept SSPI security context"), r);
    1470             :         }
    1471             : 
    1472             :         /*
    1473             :          * Overwrite the current context with the one we just received. If
    1474             :          * sspictx is NULL it was the first loop and we need to allocate a
    1475             :          * buffer for it. On subsequent runs, we can just overwrite the buffer
    1476             :          * contents since the size does not change.
    1477             :          */
    1478             :         if (sspictx == NULL)
    1479             :         {
    1480             :             sspictx = malloc(sizeof(CtxtHandle));
    1481             :             if (sspictx == NULL)
    1482             :                 ereport(ERROR,
    1483             :                         (errmsg("out of memory")));
    1484             :         }
    1485             : 
    1486             :         memcpy(sspictx, &newctx, sizeof(CtxtHandle));
    1487             : 
    1488             :         if (r == SEC_I_CONTINUE_NEEDED)
    1489             :             elog(DEBUG4, "SSPI continue needed");
    1490             : 
    1491             :     } while (r == SEC_I_CONTINUE_NEEDED);
    1492             : 
    1493             : 
    1494             :     /*
    1495             :      * Release service principal credentials
    1496             :      */
    1497             :     FreeCredentialsHandle(&sspicred);
    1498             : 
    1499             : 
    1500             :     /*
    1501             :      * SEC_E_OK indicates that authentication is now complete.
    1502             :      *
    1503             :      * Get the name of the user that authenticated, and compare it to the pg
    1504             :      * username that was specified for the connection.
    1505             :      *
    1506             :      * MingW is missing the export for QuerySecurityContextToken in the
    1507             :      * secur32 library, so we have to load it dynamically.
    1508             :      */
    1509             : 
    1510             :     secur32 = LoadLibrary("SECUR32.DLL");
    1511             :     if (secur32 == NULL)
    1512             :         ereport(ERROR,
    1513             :                 (errmsg_internal("could not load secur32.dll: error code %lu",
    1514             :                                  GetLastError())));
    1515             : 
    1516             :     _QuerySecurityContextToken = (QUERY_SECURITY_CONTEXT_TOKEN_FN)
    1517             :         GetProcAddress(secur32, "QuerySecurityContextToken");
    1518             :     if (_QuerySecurityContextToken == NULL)
    1519             :     {
    1520             :         FreeLibrary(secur32);
    1521             :         ereport(ERROR,
    1522             :                 (errmsg_internal("could not locate QuerySecurityContextToken in secur32.dll: error code %lu",
    1523             :                                  GetLastError())));
    1524             :     }
    1525             : 
    1526             :     r = (_QuerySecurityContextToken) (sspictx, &token);
    1527             :     if (r != SEC_E_OK)
    1528             :     {
    1529             :         FreeLibrary(secur32);
    1530             :         pg_SSPI_error(ERROR,
    1531             :                       _("could not get token from SSPI security context"), r);
    1532             :     }
    1533             : 
    1534             :     FreeLibrary(secur32);
    1535             : 
    1536             :     /*
    1537             :      * No longer need the security context, everything from here on uses the
    1538             :      * token instead.
    1539             :      */
    1540             :     DeleteSecurityContext(sspictx);
    1541             :     free(sspictx);
    1542             : 
    1543             :     if (!GetTokenInformation(token, TokenUser, NULL, 0, &retlen) && GetLastError() != 122)
    1544             :         ereport(ERROR,
    1545             :                 (errmsg_internal("could not get token information buffer size: error code %lu",
    1546             :                                  GetLastError())));
    1547             : 
    1548             :     tokenuser = malloc(retlen);
    1549             :     if (tokenuser == NULL)
    1550             :         ereport(ERROR,
    1551             :                 (errmsg("out of memory")));
    1552             : 
    1553             :     if (!GetTokenInformation(token, TokenUser, tokenuser, retlen, &retlen))
    1554             :         ereport(ERROR,
    1555             :                 (errmsg_internal("could not get token information: error code %lu",
    1556             :                                  GetLastError())));
    1557             : 
    1558             :     CloseHandle(token);
    1559             : 
    1560             :     if (!LookupAccountSid(NULL, tokenuser->User.Sid, accountname, &accountnamesize,
    1561             :                           domainname, &domainnamesize, &accountnameuse))
    1562             :         ereport(ERROR,
    1563             :                 (errmsg_internal("could not look up account SID: error code %lu",
    1564             :                                  GetLastError())));
    1565             : 
    1566             :     free(tokenuser);
    1567             : 
    1568             :     if (!port->hba->compat_realm)
    1569             :     {
    1570             :         int         status = pg_SSPI_make_upn(accountname, sizeof(accountname),
    1571             :                                               domainname, sizeof(domainname),
    1572             :                                               port->hba->upn_username);
    1573             : 
    1574             :         if (status != STATUS_OK)
    1575             :             /* Error already reported from pg_SSPI_make_upn */
    1576             :             return status;
    1577             :     }
    1578             : 
    1579             :     /*
    1580             :      * Compare realm/domain if requested. In SSPI, always compare case
    1581             :      * insensitive.
    1582             :      */
    1583             :     if (port->hba->krb_realm && strlen(port->hba->krb_realm))
    1584             :     {
    1585             :         if (pg_strcasecmp(port->hba->krb_realm, domainname) != 0)
    1586             :         {
    1587             :             elog(DEBUG2,
    1588             :                  "SSPI domain (%s) and configured domain (%s) don't match",
    1589             :                  domainname, port->hba->krb_realm);
    1590             : 
    1591             :             return STATUS_ERROR;
    1592             :         }
    1593             :     }
    1594             : 
    1595             :     /*
    1596             :      * We have the username (without domain/realm) in accountname, compare to
    1597             :      * the supplied value. In SSPI, always compare case insensitive.
    1598             :      *
    1599             :      * If set to include realm, append it in <username>@<realm> format.
    1600             :      */
    1601             :     if (port->hba->include_realm)
    1602             :     {
    1603             :         char       *namebuf;
    1604             :         int         retval;
    1605             : 
    1606             :         namebuf = psprintf("%s@%s", accountname, domainname);
    1607             :         retval = check_usermap(port->hba->usermap, port->user_name, namebuf, true);
    1608             :         pfree(namebuf);
    1609             :         return retval;
    1610             :     }
    1611             :     else
    1612             :         return check_usermap(port->hba->usermap, port->user_name, accountname, true);
    1613             : }
    1614             : 
    1615             : /*
    1616             :  * Replaces the domainname with the Kerberos realm name,
    1617             :  * and optionally the accountname with the Kerberos user name.
    1618             :  */
    1619             : static int
    1620             : pg_SSPI_make_upn(char *accountname,
    1621             :                  size_t accountnamesize,
    1622             :                  char *domainname,
    1623             :                  size_t domainnamesize,
    1624             :                  bool update_accountname)
    1625             : {
    1626             :     char       *samname;
    1627             :     char       *upname = NULL;
    1628             :     char       *p = NULL;
    1629             :     ULONG       upnamesize = 0;
    1630             :     size_t      upnamerealmsize;
    1631             :     BOOLEAN     res;
    1632             : 
    1633             :     /*
    1634             :      * Build SAM name (DOMAIN\user), then translate to UPN
    1635             :      * (user@kerberos.realm). The realm name is returned in lower case, but
    1636             :      * that is fine because in SSPI auth, string comparisons are always
    1637             :      * case-insensitive.
    1638             :      */
    1639             : 
    1640             :     samname = psprintf("%s\\%s", domainname, accountname);
    1641             :     res = TranslateName(samname, NameSamCompatible, NameUserPrincipal,
    1642             :                         NULL, &upnamesize);
    1643             : 
    1644             :     if ((!res && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
    1645             :         || upnamesize == 0)
    1646             :     {
    1647             :         pfree(samname);
    1648             :         ereport(LOG,
    1649             :                 (errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
    1650             :                  errmsg("could not translate name")));
    1651             :         return STATUS_ERROR;
    1652             :     }
    1653             : 
    1654             :     /* upnamesize includes the terminating NUL. */
    1655             :     upname = palloc(upnamesize);
    1656             : 
    1657             :     res = TranslateName(samname, NameSamCompatible, NameUserPrincipal,
    1658             :                         upname, &upnamesize);
    1659             : 
    1660             :     pfree(samname);
    1661             :     if (res)
    1662             :         p = strchr(upname, '@');
    1663             : 
    1664             :     if (!res || p == NULL)
    1665             :     {
    1666             :         pfree(upname);
    1667             :         ereport(LOG,
    1668             :                 (errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
    1669             :                  errmsg("could not translate name")));
    1670             :         return STATUS_ERROR;
    1671             :     }
    1672             : 
    1673             :     /* Length of realm name after the '@', including the NUL. */
    1674             :     upnamerealmsize = upnamesize - (p - upname + 1);
    1675             : 
    1676             :     /* Replace domainname with realm name. */
    1677             :     if (upnamerealmsize > domainnamesize)
    1678             :     {
    1679             :         pfree(upname);
    1680             :         ereport(LOG,
    1681             :                 (errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
    1682             :                  errmsg("realm name too long")));
    1683             :         return STATUS_ERROR;
    1684             :     }
    1685             : 
    1686             :     /* Length is now safe. */
    1687             :     strcpy(domainname, p + 1);
    1688             : 
    1689             :     /* Replace account name as well (in case UPN != SAM)? */
    1690             :     if (update_accountname)
    1691             :     {
    1692             :         if ((p - upname + 1) > accountnamesize)
    1693             :         {
    1694             :             pfree(upname);
    1695             :             ereport(LOG,
    1696             :                     (errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
    1697             :                      errmsg("translated account name too long")));
    1698             :             return STATUS_ERROR;
    1699             :         }
    1700             : 
    1701             :         *p = 0;
    1702             :         strcpy(accountname, upname);
    1703             :     }
    1704             : 
    1705             :     pfree(upname);
    1706             :     return STATUS_OK;
    1707             : }
    1708             : #endif                          /* ENABLE_SSPI */
    1709             : 
    1710             : 
    1711             : 
    1712             : /*----------------------------------------------------------------
    1713             :  * Ident authentication system
    1714             :  *----------------------------------------------------------------
    1715             :  */
    1716             : 
    1717             : /*
    1718             :  *  Parse the string "*ident_response" as a response from a query to an Ident
    1719             :  *  server.  If it's a normal response indicating a user name, return true
    1720             :  *  and store the user name at *ident_user. If it's anything else,
    1721             :  *  return false.
    1722             :  */
    1723             : static bool
    1724           0 : interpret_ident_response(const char *ident_response,
    1725             :                          char *ident_user)
    1726             : {
    1727           0 :     const char *cursor = ident_response;    /* Cursor into *ident_response */
    1728             : 
    1729             :     /*
    1730             :      * Ident's response, in the telnet tradition, should end in crlf (\r\n).
    1731             :      */
    1732           0 :     if (strlen(ident_response) < 2)
    1733           0 :         return false;
    1734           0 :     else if (ident_response[strlen(ident_response) - 2] != '\r')
    1735           0 :         return false;
    1736             :     else
    1737             :     {
    1738           0 :         while (*cursor != ':' && *cursor != '\r')
    1739           0 :             cursor++;           /* skip port field */
    1740             : 
    1741           0 :         if (*cursor != ':')
    1742           0 :             return false;
    1743             :         else
    1744             :         {
    1745             :             /* We're positioned to colon before response type field */
    1746             :             char        response_type[80];
    1747             :             int         i;      /* Index into *response_type */
    1748             : 
    1749           0 :             cursor++;           /* Go over colon */
    1750           0 :             while (pg_isblank(*cursor))
    1751           0 :                 cursor++;       /* skip blanks */
    1752           0 :             i = 0;
    1753           0 :             while (*cursor != ':' && *cursor != '\r' && !pg_isblank(*cursor) &&
    1754             :                    i < (int) (sizeof(response_type) - 1))
    1755           0 :                 response_type[i++] = *cursor++;
    1756           0 :             response_type[i] = '\0';
    1757           0 :             while (pg_isblank(*cursor))
    1758           0 :                 cursor++;       /* skip blanks */
    1759           0 :             if (strcmp(response_type, "USERID") != 0)
    1760           0 :                 return false;
    1761             :             else
    1762             :             {
    1763             :                 /*
    1764             :                  * It's a USERID response.  Good.  "cursor" should be pointing
    1765             :                  * to the colon that precedes the operating system type.
    1766             :                  */
    1767           0 :                 if (*cursor != ':')
    1768           0 :                     return false;
    1769             :                 else
    1770             :                 {
    1771           0 :                     cursor++;   /* Go over colon */
    1772             :                     /* Skip over operating system field. */
    1773           0 :                     while (*cursor != ':' && *cursor != '\r')
    1774           0 :                         cursor++;
    1775           0 :                     if (*cursor != ':')
    1776           0 :                         return false;
    1777             :                     else
    1778             :                     {
    1779             :                         int         i;  /* Index into *ident_user */
    1780             : 
    1781           0 :                         cursor++;   /* Go over colon */
    1782           0 :                         while (pg_isblank(*cursor))
    1783           0 :                             cursor++;   /* skip blanks */
    1784             :                         /* Rest of line is user name.  Copy it over. */
    1785           0 :                         i = 0;
    1786           0 :                         while (*cursor != '\r' && i < IDENT_USERNAME_MAX)
    1787           0 :                             ident_user[i++] = *cursor++;
    1788           0 :                         ident_user[i] = '\0';
    1789           0 :                         return true;
    1790             :                     }
    1791             :                 }
    1792             :             }
    1793             :         }
    1794             :     }
    1795             : }
    1796             : 
    1797             : 
    1798             : /*
    1799             :  *  Talk to the ident server on host "remote_ip_addr" and find out who
    1800             :  *  owns the tcp connection from his port "remote_port" to port
    1801             :  *  "local_port_addr" on host "local_ip_addr".  Return the user name the
    1802             :  *  ident server gives as "*ident_user".
    1803             :  *
    1804             :  *  IP addresses and port numbers are in network byte order.
    1805             :  *
    1806             :  *  But iff we're unable to get the information from ident, return false.
    1807             :  *
    1808             :  *  XXX: Using WaitLatchOrSocket() and doing a CHECK_FOR_INTERRUPTS() if the
    1809             :  *  latch was set would improve the responsiveness to timeouts/cancellations.
    1810             :  */
    1811             : static int
    1812           0 : ident_inet(hbaPort *port)
    1813             : {
    1814           0 :     const SockAddr remote_addr = port->raddr;
    1815           0 :     const SockAddr local_addr = port->laddr;
    1816             :     char        ident_user[IDENT_USERNAME_MAX + 1];
    1817           0 :     pgsocket    sock_fd = PGINVALID_SOCKET; /* for talking to Ident server */
    1818             :     int         rc;             /* Return code from a locally called function */
    1819             :     bool        ident_return;
    1820             :     char        remote_addr_s[NI_MAXHOST];
    1821             :     char        remote_port[NI_MAXSERV];
    1822             :     char        local_addr_s[NI_MAXHOST];
    1823             :     char        local_port[NI_MAXSERV];
    1824             :     char        ident_port[NI_MAXSERV];
    1825             :     char        ident_query[80];
    1826             :     char        ident_response[80 + IDENT_USERNAME_MAX];
    1827           0 :     struct addrinfo *ident_serv = NULL,
    1828           0 :                *la = NULL,
    1829             :                 hints;
    1830             : 
    1831             :     /*
    1832             :      * Might look a little weird to first convert it to text and then back to
    1833             :      * sockaddr, but it's protocol independent.
    1834             :      */
    1835           0 :     pg_getnameinfo_all(&remote_addr.addr, remote_addr.salen,
    1836             :                        remote_addr_s, sizeof(remote_addr_s),
    1837             :                        remote_port, sizeof(remote_port),
    1838             :                        NI_NUMERICHOST | NI_NUMERICSERV);
    1839           0 :     pg_getnameinfo_all(&local_addr.addr, local_addr.salen,
    1840             :                        local_addr_s, sizeof(local_addr_s),
    1841             :                        local_port, sizeof(local_port),
    1842             :                        NI_NUMERICHOST | NI_NUMERICSERV);
    1843             : 
    1844           0 :     snprintf(ident_port, sizeof(ident_port), "%d", IDENT_PORT);
    1845           0 :     hints.ai_flags = AI_NUMERICHOST;
    1846           0 :     hints.ai_family = remote_addr.addr.ss_family;
    1847           0 :     hints.ai_socktype = SOCK_STREAM;
    1848           0 :     hints.ai_protocol = 0;
    1849           0 :     hints.ai_addrlen = 0;
    1850           0 :     hints.ai_canonname = NULL;
    1851           0 :     hints.ai_addr = NULL;
    1852           0 :     hints.ai_next = NULL;
    1853           0 :     rc = pg_getaddrinfo_all(remote_addr_s, ident_port, &hints, &ident_serv);
    1854           0 :     if (rc || !ident_serv)
    1855             :     {
    1856             :         /* we don't expect this to happen */
    1857           0 :         ident_return = false;
    1858           0 :         goto ident_inet_done;
    1859             :     }
    1860             : 
    1861           0 :     hints.ai_flags = AI_NUMERICHOST;
    1862           0 :     hints.ai_family = local_addr.addr.ss_family;
    1863           0 :     hints.ai_socktype = SOCK_STREAM;
    1864           0 :     hints.ai_protocol = 0;
    1865           0 :     hints.ai_addrlen = 0;
    1866           0 :     hints.ai_canonname = NULL;
    1867           0 :     hints.ai_addr = NULL;
    1868           0 :     hints.ai_next = NULL;
    1869           0 :     rc = pg_getaddrinfo_all(local_addr_s, NULL, &hints, &la);
    1870           0 :     if (rc || !la)
    1871             :     {
    1872             :         /* we don't expect this to happen */
    1873           0 :         ident_return = false;
    1874           0 :         goto ident_inet_done;
    1875             :     }
    1876             : 
    1877           0 :     sock_fd = socket(ident_serv->ai_family, ident_serv->ai_socktype,
    1878           0 :                      ident_serv->ai_protocol);
    1879           0 :     if (sock_fd == PGINVALID_SOCKET)
    1880             :     {
    1881           0 :         ereport(LOG,
    1882             :                 (errcode_for_socket_access(),
    1883             :                  errmsg("could not create socket for Ident connection: %m")));
    1884           0 :         ident_return = false;
    1885           0 :         goto ident_inet_done;
    1886             :     }
    1887             : 
    1888             :     /*
    1889             :      * Bind to the address which the client originally contacted, otherwise
    1890             :      * the ident server won't be able to match up the right connection. This
    1891             :      * is necessary if the PostgreSQL server is running on an IP alias.
    1892             :      */
    1893           0 :     rc = bind(sock_fd, la->ai_addr, la->ai_addrlen);
    1894           0 :     if (rc != 0)
    1895             :     {
    1896           0 :         ereport(LOG,
    1897             :                 (errcode_for_socket_access(),
    1898             :                  errmsg("could not bind to local address \"%s\": %m",
    1899             :                         local_addr_s)));
    1900           0 :         ident_return = false;
    1901           0 :         goto ident_inet_done;
    1902             :     }
    1903             : 
    1904           0 :     rc = connect(sock_fd, ident_serv->ai_addr,
    1905           0 :                  ident_serv->ai_addrlen);
    1906           0 :     if (rc != 0)
    1907             :     {
    1908           0 :         ereport(LOG,
    1909             :                 (errcode_for_socket_access(),
    1910             :                  errmsg("could not connect to Ident server at address \"%s\", port %s: %m",
    1911             :                         remote_addr_s, ident_port)));
    1912           0 :         ident_return = false;
    1913           0 :         goto ident_inet_done;
    1914             :     }
    1915             : 
    1916             :     /* The query we send to the Ident server */
    1917           0 :     snprintf(ident_query, sizeof(ident_query), "%s,%s\r\n",
    1918             :              remote_port, local_port);
    1919             : 
    1920             :     /* loop in case send is interrupted */
    1921             :     do
    1922             :     {
    1923           0 :         CHECK_FOR_INTERRUPTS();
    1924             : 
    1925           0 :         rc = send(sock_fd, ident_query, strlen(ident_query), 0);
    1926           0 :     } while (rc < 0 && errno == EINTR);
    1927             : 
    1928           0 :     if (rc < 0)
    1929             :     {
    1930           0 :         ereport(LOG,
    1931             :                 (errcode_for_socket_access(),
    1932             :                  errmsg("could not send query to Ident server at address \"%s\", port %s: %m",
    1933             :                         remote_addr_s, ident_port)));
    1934           0 :         ident_return = false;
    1935           0 :         goto ident_inet_done;
    1936             :     }
    1937             : 
    1938             :     do
    1939             :     {
    1940           0 :         CHECK_FOR_INTERRUPTS();
    1941             : 
    1942           0 :         rc = recv(sock_fd, ident_response, sizeof(ident_response) - 1, 0);
    1943           0 :     } while (rc < 0 && errno == EINTR);
    1944             : 
    1945           0 :     if (rc < 0)
    1946             :     {
    1947           0 :         ereport(LOG,
    1948             :                 (errcode_for_socket_access(),
    1949             :                  errmsg("could not receive response from Ident server at address \"%s\", port %s: %m",
    1950             :                         remote_addr_s, ident_port)));
    1951           0 :         ident_return = false;
    1952           0 :         goto ident_inet_done;
    1953             :     }
    1954             : 
    1955           0 :     ident_response[rc] = '\0';
    1956           0 :     ident_return = interpret_ident_response(ident_response, ident_user);
    1957           0 :     if (!ident_return)
    1958           0 :         ereport(LOG,
    1959             :                 (errmsg("invalidly formatted response from Ident server: \"%s\"",
    1960             :                         ident_response)));
    1961             : 
    1962             : ident_inet_done:
    1963           0 :     if (sock_fd != PGINVALID_SOCKET)
    1964           0 :         closesocket(sock_fd);
    1965           0 :     if (ident_serv)
    1966           0 :         pg_freeaddrinfo_all(remote_addr.addr.ss_family, ident_serv);
    1967           0 :     if (la)
    1968           0 :         pg_freeaddrinfo_all(local_addr.addr.ss_family, la);
    1969             : 
    1970           0 :     if (ident_return)
    1971             :         /* Success! Check the usermap */
    1972           0 :         return check_usermap(port->hba->usermap, port->user_name, ident_user, false);
    1973           0 :     return STATUS_ERROR;
    1974             : }
    1975             : 
    1976             : /*
    1977             :  *  Ask kernel about the credentials of the connecting process,
    1978             :  *  determine the symbolic name of the corresponding user, and check
    1979             :  *  if valid per the usermap.
    1980             :  *
    1981             :  *  Iff authorized, return STATUS_OK, otherwise return STATUS_ERROR.
    1982             :  */
    1983             : #ifdef HAVE_UNIX_SOCKETS
    1984             : 
    1985             : static int
    1986           0 : auth_peer(hbaPort *port)
    1987             : {
    1988             :     char        ident_user[IDENT_USERNAME_MAX + 1];
    1989             :     uid_t       uid;
    1990             :     gid_t       gid;
    1991             :     struct passwd *pw;
    1992             : 
    1993           0 :     if (getpeereid(port->sock, &uid, &gid) != 0)
    1994             :     {
    1995             :         /* Provide special error message if getpeereid is a stub */
    1996           0 :         if (errno == ENOSYS)
    1997           0 :             ereport(LOG,
    1998             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1999             :                      errmsg("peer authentication is not supported on this platform")));
    2000             :         else
    2001           0 :             ereport(LOG,
    2002             :                     (errcode_for_socket_access(),
    2003             :                      errmsg("could not get peer credentials: %m")));
    2004           0 :         return STATUS_ERROR;
    2005             :     }
    2006             : 
    2007           0 :     errno = 0;                  /* clear errno before call */
    2008           0 :     pw = getpwuid(uid);
    2009           0 :     if (!pw)
    2010             :     {
    2011           0 :         int         save_errno = errno;
    2012             : 
    2013           0 :         ereport(LOG,
    2014             :                 (errmsg("could not look up local user ID %ld: %s",
    2015             :                         (long) uid,
    2016             :                         save_errno ? strerror(save_errno) : _("user does not exist"))));
    2017           0 :         return STATUS_ERROR;
    2018             :     }
    2019             : 
    2020           0 :     strlcpy(ident_user, pw->pw_name, IDENT_USERNAME_MAX + 1);
    2021             : 
    2022           0 :     return check_usermap(port->hba->usermap, port->user_name, ident_user, false);
    2023             : }
    2024             : #endif                          /* HAVE_UNIX_SOCKETS */
    2025             : 
    2026             : 
    2027             : /*----------------------------------------------------------------
    2028             :  * PAM authentication system
    2029             :  *----------------------------------------------------------------
    2030             :  */
    2031             : #ifdef USE_PAM
    2032             : 
    2033             : /*
    2034             :  * PAM conversation function
    2035             :  */
    2036             : 
    2037             : static int
    2038           0 : pam_passwd_conv_proc(int num_msg, const struct pam_message **msg,
    2039             :                      struct pam_response **resp, void *appdata_ptr)
    2040             : {
    2041             :     const char *passwd;
    2042             :     struct pam_response *reply;
    2043             :     int         i;
    2044             : 
    2045           0 :     if (appdata_ptr)
    2046           0 :         passwd = (char *) appdata_ptr;
    2047             :     else
    2048             :     {
    2049             :         /*
    2050             :          * Workaround for Solaris 2.6 where the PAM library is broken and does
    2051             :          * not pass appdata_ptr to the conversation routine
    2052             :          */
    2053           0 :         passwd = pam_passwd;
    2054             :     }
    2055             : 
    2056           0 :     *resp = NULL;               /* in case of error exit */
    2057             : 
    2058           0 :     if (num_msg <= 0 || num_msg > PAM_MAX_NUM_MSG)
    2059           0 :         return PAM_CONV_ERR;
    2060             : 
    2061             :     /*
    2062             :      * Explicitly not using palloc here - PAM will free this memory in
    2063             :      * pam_end()
    2064             :      */
    2065           0 :     if ((reply = calloc(num_msg, sizeof(struct pam_response))) == NULL)
    2066             :     {
    2067           0 :         ereport(LOG,
    2068             :                 (errcode(ERRCODE_OUT_OF_MEMORY),
    2069             :                  errmsg("out of memory")));
    2070           0 :         return PAM_CONV_ERR;
    2071             :     }
    2072             : 
    2073           0 :     for (i = 0; i < num_msg; i++)
    2074             :     {
    2075           0 :         switch (msg[i]->msg_style)
    2076             :         {
    2077             :             case PAM_PROMPT_ECHO_OFF:
    2078           0 :                 if (strlen(passwd) == 0)
    2079             :                 {
    2080             :                     /*
    2081             :                      * Password wasn't passed to PAM the first time around -
    2082             :                      * let's go ask the client to send a password, which we
    2083             :                      * then stuff into PAM.
    2084             :                      */
    2085           0 :                     sendAuthRequest(pam_port_cludge, AUTH_REQ_PASSWORD, NULL, 0);
    2086           0 :                     passwd = recv_password_packet(pam_port_cludge);
    2087           0 :                     if (passwd == NULL)
    2088             :                     {
    2089             :                         /*
    2090             :                          * Client didn't want to send password.  We
    2091             :                          * intentionally do not log anything about this.
    2092             :                          */
    2093           0 :                         goto fail;
    2094             :                     }
    2095             :                 }
    2096           0 :                 if ((reply[i].resp = strdup(passwd)) == NULL)
    2097           0 :                     goto fail;
    2098           0 :                 reply[i].resp_retcode = PAM_SUCCESS;
    2099           0 :                 break;
    2100             :             case PAM_ERROR_MSG:
    2101           0 :                 ereport(LOG,
    2102             :                         (errmsg("error from underlying PAM layer: %s",
    2103             :                                 msg[i]->msg)));
    2104             :                 /* FALL THROUGH */
    2105             :             case PAM_TEXT_INFO:
    2106             :                 /* we don't bother to log TEXT_INFO messages */
    2107           0 :                 if ((reply[i].resp = strdup("")) == NULL)
    2108           0 :                     goto fail;
    2109           0 :                 reply[i].resp_retcode = PAM_SUCCESS;
    2110           0 :                 break;
    2111             :             default:
    2112           0 :                 elog(LOG, "unsupported PAM conversation %d/\"%s\"",
    2113             :                      msg[i]->msg_style,
    2114             :                      msg[i]->msg ? msg[i]->msg : "(none)");
    2115           0 :                 goto fail;
    2116             :         }
    2117             :     }
    2118             : 
    2119           0 :     *resp = reply;
    2120           0 :     return PAM_SUCCESS;
    2121             : 
    2122             : fail:
    2123             :     /* free up whatever we allocated */
    2124           0 :     for (i = 0; i < num_msg; i++)
    2125             :     {
    2126           0 :         if (reply[i].resp != NULL)
    2127           0 :             free(reply[i].resp);
    2128             :     }
    2129           0 :     free(reply);
    2130             : 
    2131           0 :     return PAM_CONV_ERR;
    2132             : }
    2133             : 
    2134             : 
    2135             : /*
    2136             :  * Check authentication against PAM.
    2137             :  */
    2138             : static int
    2139           0 : CheckPAMAuth(Port *port, const char *user, const char *password)
    2140             : {
    2141             :     int         retval;
    2142           0 :     pam_handle_t *pamh = NULL;
    2143             : 
    2144             :     /*
    2145             :      * We can't entirely rely on PAM to pass through appdata --- it appears
    2146             :      * not to work on at least Solaris 2.6.  So use these ugly static
    2147             :      * variables instead.
    2148             :      */
    2149           0 :     pam_passwd = password;
    2150           0 :     pam_port_cludge = port;
    2151             : 
    2152             :     /*
    2153             :      * Set the application data portion of the conversation struct.  This is
    2154             :      * later used inside the PAM conversation to pass the password to the
    2155             :      * authentication module.
    2156             :      */
    2157           0 :     pam_passw_conv.appdata_ptr = unconstify(char *, password);  /* from password above,
    2158             :                                                                  * not allocated */
    2159             : 
    2160             :     /* Optionally, one can set the service name in pg_hba.conf */
    2161           0 :     if (port->hba->pamservice && port->hba->pamservice[0] != '\0')
    2162           0 :         retval = pam_start(port->hba->pamservice, "pgsql@",
    2163             :                            &pam_passw_conv, &pamh);
    2164             :     else
    2165           0 :         retval = pam_start(PGSQL_PAM_SERVICE, "pgsql@",
    2166             :                            &pam_passw_conv, &pamh);
    2167             : 
    2168           0 :     if (retval != PAM_SUCCESS)
    2169             :     {
    2170           0 :         ereport(LOG,
    2171             :                 (errmsg("could not create PAM authenticator: %s",
    2172             :                         pam_strerror(pamh, retval))));
    2173           0 :         pam_passwd = NULL;      /* Unset pam_passwd */
    2174           0 :         return STATUS_ERROR;
    2175             :     }
    2176             : 
    2177           0 :     retval = pam_set_item(pamh, PAM_USER, user);
    2178             : 
    2179           0 :     if (retval != PAM_SUCCESS)
    2180             :     {
    2181           0 :         ereport(LOG,
    2182             :                 (errmsg("pam_set_item(PAM_USER) failed: %s",
    2183             :                         pam_strerror(pamh, retval))));
    2184           0 :         pam_passwd = NULL;      /* Unset pam_passwd */
    2185           0 :         return STATUS_ERROR;
    2186             :     }
    2187             : 
    2188           0 :     if (port->hba->conntype != ctLocal)
    2189             :     {
    2190             :         char        hostinfo[NI_MAXHOST];
    2191             :         int         flags;
    2192             : 
    2193           0 :         if (port->hba->pam_use_hostname)
    2194           0 :             flags = 0;
    2195             :         else
    2196           0 :             flags = NI_NUMERICHOST | NI_NUMERICSERV;
    2197             : 
    2198           0 :         retval = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
    2199             :                                     hostinfo, sizeof(hostinfo), NULL, 0,
    2200             :                                     flags);
    2201           0 :         if (retval != 0)
    2202             :         {
    2203           0 :             ereport(WARNING,
    2204             :                     (errmsg_internal("pg_getnameinfo_all() failed: %s",
    2205             :                                      gai_strerror(retval))));
    2206           0 :             return STATUS_ERROR;
    2207             :         }
    2208             : 
    2209           0 :         retval = pam_set_item(pamh, PAM_RHOST, hostinfo);
    2210             : 
    2211           0 :         if (retval != PAM_SUCCESS)
    2212             :         {
    2213           0 :             ereport(LOG,
    2214             :                     (errmsg("pam_set_item(PAM_RHOST) failed: %s",
    2215             :                             pam_strerror(pamh, retval))));
    2216           0 :             pam_passwd = NULL;
    2217           0 :             return STATUS_ERROR;
    2218             :         }
    2219             :     }
    2220             : 
    2221           0 :     retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv);
    2222             : 
    2223           0 :     if (retval != PAM_SUCCESS)
    2224             :     {
    2225           0 :         ereport(LOG,
    2226             :                 (errmsg("pam_set_item(PAM_CONV) failed: %s",
    2227             :                         pam_strerror(pamh, retval))));
    2228           0 :         pam_passwd = NULL;      /* Unset pam_passwd */
    2229           0 :         return STATUS_ERROR;
    2230             :     }
    2231             : 
    2232           0 :     retval = pam_authenticate(pamh, 0);
    2233             : 
    2234           0 :     if (retval != PAM_SUCCESS)
    2235             :     {
    2236           0 :         ereport(LOG,
    2237             :                 (errmsg("pam_authenticate failed: %s",
    2238             :                         pam_strerror(pamh, retval))));
    2239           0 :         pam_passwd = NULL;      /* Unset pam_passwd */
    2240           0 :         return STATUS_ERROR;
    2241             :     }
    2242             : 
    2243           0 :     retval = pam_acct_mgmt(pamh, 0);
    2244             : 
    2245           0 :     if (retval != PAM_SUCCESS)
    2246             :     {
    2247           0 :         ereport(LOG,
    2248             :                 (errmsg("pam_acct_mgmt failed: %s",
    2249             :                         pam_strerror(pamh, retval))));
    2250           0 :         pam_passwd = NULL;      /* Unset pam_passwd */
    2251           0 :         return STATUS_ERROR;
    2252             :     }
    2253             : 
    2254           0 :     retval = pam_end(pamh, retval);
    2255             : 
    2256           0 :     if (retval != PAM_SUCCESS)
    2257             :     {
    2258           0 :         ereport(LOG,
    2259             :                 (errmsg("could not release PAM authenticator: %s",
    2260             :                         pam_strerror(pamh, retval))));
    2261             :     }
    2262             : 
    2263           0 :     pam_passwd = NULL;          /* Unset pam_passwd */
    2264             : 
    2265           0 :     return (retval == PAM_SUCCESS ? STATUS_OK : STATUS_ERROR);
    2266             : }
    2267             : #endif                          /* USE_PAM */
    2268             : 
    2269             : 
    2270             : /*----------------------------------------------------------------
    2271             :  * BSD authentication system
    2272             :  *----------------------------------------------------------------
    2273             :  */
    2274             : #ifdef USE_BSD_AUTH
    2275             : static int
    2276             : CheckBSDAuth(Port *port, char *user)
    2277             : {
    2278             :     char       *passwd;
    2279             :     int         retval;
    2280             : 
    2281             :     /* Send regular password request to client, and get the response */
    2282             :     sendAuthRequest(port, AUTH_REQ_PASSWORD, NULL, 0);
    2283             : 
    2284             :     passwd = recv_password_packet(port);
    2285             :     if (passwd == NULL)
    2286             :         return STATUS_EOF;
    2287             : 
    2288             :     /*
    2289             :      * Ask the BSD auth system to verify password.  Note that auth_userokay
    2290             :      * will overwrite the password string with zeroes, but it's just a
    2291             :      * temporary string so we don't care.
    2292             :      */
    2293             :     retval = auth_userokay(user, NULL, "auth-postgresql", passwd);
    2294             : 
    2295             :     pfree(passwd);
    2296             : 
    2297             :     if (!retval)
    2298             :         return STATUS_ERROR;
    2299             : 
    2300             :     return STATUS_OK;
    2301             : }
    2302             : #endif                          /* USE_BSD_AUTH */
    2303             : 
    2304             : 
    2305             : /*----------------------------------------------------------------
    2306             :  * LDAP authentication system
    2307             :  *----------------------------------------------------------------
    2308             :  */
    2309             : #ifdef USE_LDAP
    2310             : 
    2311             : static int  errdetail_for_ldap(LDAP *ldap);
    2312             : 
    2313             : /*
    2314             :  * Initialize a connection to the LDAP server, including setting up
    2315             :  * TLS if requested.
    2316             :  */
    2317             : static int
    2318          70 : InitializeLDAPConnection(Port *port, LDAP **ldap)
    2319             : {
    2320             :     const char *scheme;
    2321          70 :     int         ldapversion = LDAP_VERSION3;
    2322             :     int         r;
    2323             : 
    2324          70 :     scheme = port->hba->ldapscheme;
    2325          70 :     if (scheme == NULL)
    2326          40 :         scheme = "ldap";
    2327             : #ifdef WIN32
    2328             :     if (strcmp(scheme, "ldaps") == 0)
    2329             :         *ldap = ldap_sslinit(port->hba->ldapserver, port->hba->ldapport, 1);
    2330             :     else
    2331             :         *ldap = ldap_init(port->hba->ldapserver, port->hba->ldapport);
    2332             :     if (!*ldap)
    2333             :     {
    2334             :         ereport(LOG,
    2335             :                 (errmsg("could not initialize LDAP: error code %d",
    2336             :                         (int) LdapGetLastError())));
    2337             : 
    2338             :         return STATUS_ERROR;
    2339             :     }
    2340             : #else
    2341             : #ifdef HAVE_LDAP_INITIALIZE
    2342             : 
    2343             :     /*
    2344             :      * OpenLDAP provides a non-standard extension ldap_initialize() that takes
    2345             :      * a list of URIs, allowing us to request "ldaps" instead of "ldap".  It
    2346             :      * also provides ldap_domain2hostlist() to find LDAP servers automatically
    2347             :      * using DNS SRV.  They were introduced in the same version, so for now we
    2348             :      * don't have an extra configure check for the latter.
    2349             :      */
    2350             :     {
    2351             :         StringInfoData uris;
    2352          70 :         char       *hostlist = NULL;
    2353             :         char       *p;
    2354             :         bool        append_port;
    2355             : 
    2356             :         /* We'll build a space-separated scheme://hostname:port list here */
    2357          70 :         initStringInfo(&uris);
    2358             : 
    2359             :         /*
    2360             :          * If pg_hba.conf provided no hostnames, we can ask OpenLDAP to try to
    2361             :          * find some by extracting a domain name from the base DN and looking
    2362             :          * up DSN SRV records for _ldap._tcp.<domain>.
    2363             :          */
    2364          70 :         if (!port->hba->ldapserver || port->hba->ldapserver[0] == '\0')
    2365           0 :         {
    2366             :             char       *domain;
    2367             : 
    2368             :             /* ou=blah,dc=foo,dc=bar -> foo.bar */
    2369           0 :             if (ldap_dn2domain(port->hba->ldapbasedn, &domain))
    2370             :             {
    2371           0 :                 ereport(LOG,
    2372             :                         (errmsg("could not extract domain name from ldapbasedn")));
    2373           0 :                 return STATUS_ERROR;
    2374             :             }
    2375             : 
    2376             :             /* Look up a list of LDAP server hosts and port numbers */
    2377           0 :             if (ldap_domain2hostlist(domain, &hostlist))
    2378             :             {
    2379           0 :                 ereport(LOG,
    2380             :                         (errmsg("LDAP authentication could not find DNS SRV records for \"%s\"",
    2381             :                                 domain),
    2382             :                          (errhint("Set an LDAP server name explicitly."))));
    2383           0 :                 ldap_memfree(domain);
    2384           0 :                 return STATUS_ERROR;
    2385             :             }
    2386           0 :             ldap_memfree(domain);
    2387             : 
    2388             :             /* We have a space-separated list of host:port entries */
    2389           0 :             p = hostlist;
    2390           0 :             append_port = false;
    2391             :         }
    2392             :         else
    2393             :         {
    2394             :             /* We have a space-separated list of hosts from pg_hba.conf */
    2395          70 :             p = port->hba->ldapserver;
    2396          70 :             append_port = true;
    2397             :         }
    2398             : 
    2399             :         /* Convert the list of host[:port] entries to full URIs */
    2400             :         do
    2401             :         {
    2402             :             size_t      size;
    2403             : 
    2404             :             /* Find the span of the next entry */
    2405          80 :             size = strcspn(p, " ");
    2406             : 
    2407             :             /* Append a space separator if this isn't the first URI */
    2408          80 :             if (uris.len > 0)
    2409          10 :                 appendStringInfoChar(&uris, ' ');
    2410             : 
    2411             :             /* Append scheme://host:port */
    2412          80 :             appendStringInfoString(&uris, scheme);
    2413          80 :             appendStringInfoString(&uris, "://");
    2414          80 :             appendBinaryStringInfo(&uris, p, size);
    2415          80 :             if (append_port)
    2416          80 :                 appendStringInfo(&uris, ":%d", port->hba->ldapport);
    2417             : 
    2418             :             /* Step over this entry and any number of trailing spaces */
    2419          80 :             p += size;
    2420         170 :             while (*p == ' ')
    2421          10 :                 ++p;
    2422          80 :         } while (*p);
    2423             : 
    2424             :         /* Free memory from OpenLDAP if we looked up SRV records */
    2425          70 :         if (hostlist)
    2426           0 :             ldap_memfree(hostlist);
    2427             : 
    2428             :         /* Finally, try to connect using the URI list */
    2429          70 :         r = ldap_initialize(ldap, uris.data);
    2430          70 :         pfree(uris.data);
    2431          70 :         if (r != LDAP_SUCCESS)
    2432             :         {
    2433           0 :             ereport(LOG,
    2434             :                     (errmsg("could not initialize LDAP: %s",
    2435             :                             ldap_err2string(r))));
    2436             : 
    2437           0 :             return STATUS_ERROR;
    2438             :         }
    2439             :     }
    2440             : #else
    2441             :     if (strcmp(scheme, "ldaps") == 0)
    2442             :     {
    2443             :         ereport(LOG,
    2444             :                 (errmsg("ldaps not supported with this LDAP library")));
    2445             : 
    2446             :         return STATUS_ERROR;
    2447             :     }
    2448             :     *ldap = ldap_init(port->hba->ldapserver, port->hba->ldapport);
    2449             :     if (!*ldap)
    2450             :     {
    2451             :         ereport(LOG,
    2452             :                 (errmsg("could not initialize LDAP: %m")));
    2453             : 
    2454             :         return STATUS_ERROR;
    2455             :     }
    2456             : #endif
    2457             : #endif
    2458             : 
    2459          70 :     if ((r = ldap_set_option(*ldap, LDAP_OPT_PROTOCOL_VERSION, &ldapversion)) != LDAP_SUCCESS)
    2460             :     {
    2461           0 :         ereport(LOG,
    2462             :                 (errmsg("could not set LDAP protocol version: %s",
    2463             :                         ldap_err2string(r)),
    2464             :                  errdetail_for_ldap(*ldap)));
    2465           0 :         ldap_unbind(*ldap);
    2466           0 :         return STATUS_ERROR;
    2467             :     }
    2468             : 
    2469          70 :     if (port->hba->ldaptls)
    2470             :     {
    2471             : #ifndef WIN32
    2472           4 :         if ((r = ldap_start_tls_s(*ldap, NULL, NULL)) != LDAP_SUCCESS)
    2473             : #else
    2474             :         static __ldap_start_tls_sA _ldap_start_tls_sA = NULL;
    2475             : 
    2476             :         if (_ldap_start_tls_sA == NULL)
    2477             :         {
    2478             :             /*
    2479             :              * Need to load this function dynamically because it does not
    2480             :              * exist on Windows 2000, and causes a load error for the whole
    2481             :              * exe if referenced.
    2482             :              */
    2483             :             HANDLE      ldaphandle;
    2484             : 
    2485             :             ldaphandle = LoadLibrary("WLDAP32.DLL");
    2486             :             if (ldaphandle == NULL)
    2487             :             {
    2488             :                 /*
    2489             :                  * should never happen since we import other files from
    2490             :                  * wldap32, but check anyway
    2491             :                  */
    2492             :                 ereport(LOG,
    2493             :                         (errmsg("could not load wldap32.dll")));
    2494             :                 ldap_unbind(*ldap);
    2495             :                 return STATUS_ERROR;
    2496             :             }
    2497             :             _ldap_start_tls_sA = (__ldap_start_tls_sA) GetProcAddress(ldaphandle, "ldap_start_tls_sA");
    2498             :             if (_ldap_start_tls_sA == NULL)
    2499             :             {
    2500             :                 ereport(LOG,
    2501             :                         (errmsg("could not load function _ldap_start_tls_sA in wldap32.dll"),
    2502             :                          errdetail("LDAP over SSL is not supported on this platform.")));
    2503             :                 ldap_unbind(*ldap);
    2504             :                 return STATUS_ERROR;
    2505             :             }
    2506             : 
    2507             :             /*
    2508             :              * Leak LDAP handle on purpose, because we need the library to
    2509             :              * stay open. This is ok because it will only ever be leaked once
    2510             :              * per process and is automatically cleaned up on process exit.
    2511             :              */
    2512             :         }
    2513             :         if ((r = _ldap_start_tls_sA(*ldap, NULL, NULL, NULL, NULL)) != LDAP_SUCCESS)
    2514             : #endif
    2515             :         {
    2516           0 :             ereport(LOG,
    2517             :                     (errmsg("could not start LDAP TLS session: %s",
    2518             :                             ldap_err2string(r)),
    2519             :                      errdetail_for_ldap(*ldap)));
    2520           0 :             ldap_unbind(*ldap);
    2521           0 :             return STATUS_ERROR;
    2522             :         }
    2523             :     }
    2524             : 
    2525          70 :     return STATUS_OK;
    2526             : }
    2527             : 
    2528             : /* Placeholders recognized by FormatSearchFilter.  For now just one. */
    2529             : #define LPH_USERNAME "$username"
    2530             : #define LPH_USERNAME_LEN (sizeof(LPH_USERNAME) - 1)
    2531             : 
    2532             : /* Not all LDAP implementations define this. */
    2533             : #ifndef LDAP_NO_ATTRS
    2534             : #define LDAP_NO_ATTRS "1.1"
    2535             : #endif
    2536             : 
    2537             : /* Not all LDAP implementations define this. */
    2538             : #ifndef LDAPS_PORT
    2539             : #define LDAPS_PORT 636
    2540             : #endif
    2541             : 
    2542             : /*
    2543             :  * Return a newly allocated C string copied from "pattern" with all
    2544             :  * occurrences of the placeholder "$username" replaced with "user_name".
    2545             :  */
    2546             : static char *
    2547          16 : FormatSearchFilter(const char *pattern, const char *user_name)
    2548             : {
    2549             :     StringInfoData output;
    2550             : 
    2551          16 :     initStringInfo(&output);
    2552         254 :     while (*pattern != '\0')
    2553             :     {
    2554         222 :         if (strncmp(pattern, LPH_USERNAME, LPH_USERNAME_LEN) == 0)
    2555             :         {
    2556          26 :             appendStringInfoString(&output, user_name);
    2557          26 :             pattern += LPH_USERNAME_LEN;
    2558             :         }
    2559             :         else
    2560         196 :             appendStringInfoChar(&output, *pattern++);
    2561             :     }
    2562             : 
    2563          16 :     return output.data;
    2564             : }
    2565             : 
    2566             : /*
    2567             :  * Perform LDAP authentication
    2568             :  */
    2569             : static int
    2570          42 : CheckLDAPAuth(Port *port)
    2571             : {
    2572             :     char       *passwd;
    2573             :     LDAP       *ldap;
    2574             :     int         r;
    2575             :     char       *fulluser;
    2576             :     const char *server_name;
    2577             : 
    2578             : #ifdef HAVE_LDAP_INITIALIZE
    2579             : 
    2580             :     /*
    2581             :      * For OpenLDAP, allow empty hostname if we have a basedn.  We'll look for
    2582             :      * servers with DNS SRV records via OpenLDAP library facilities.
    2583             :      */
    2584          42 :     if ((!port->hba->ldapserver || port->hba->ldapserver[0] == '\0') &&
    2585           0 :         (!port->hba->ldapbasedn || port->hba->ldapbasedn[0] == '\0'))
    2586             :     {
    2587           0 :         ereport(LOG,
    2588             :                 (errmsg("LDAP server not specified, and no ldapbasedn")));
    2589           0 :         return STATUS_ERROR;
    2590             :     }
    2591             : #else
    2592             :     if (!port->hba->ldapserver || port->hba->ldapserver[0] == '\0')
    2593             :     {
    2594             :         ereport(LOG,
    2595             :                 (errmsg("LDAP server not specified")));
    2596             :         return STATUS_ERROR;
    2597             :     }
    2598             : #endif
    2599             : 
    2600             :     /*
    2601             :      * If we're using SRV records, we don't have a server name so we'll just
    2602             :      * show an empty string in error messages.
    2603             :      */
    2604          42 :     server_name = port->hba->ldapserver ? port->hba->ldapserver : "";
    2605             : 
    2606          42 :     if (port->hba->ldapport == 0)
    2607             :     {
    2608           0 :         if (port->hba->ldapscheme != NULL &&
    2609           0 :             strcmp(port->hba->ldapscheme, "ldaps") == 0)
    2610           0 :             port->hba->ldapport = LDAPS_PORT;
    2611             :         else
    2612           0 :             port->hba->ldapport = LDAP_PORT;
    2613             :     }
    2614             : 
    2615          42 :     sendAuthRequest(port, AUTH_REQ_PASSWORD, NULL, 0);
    2616             : 
    2617          42 :     passwd = recv_password_packet(port);
    2618          42 :     if (passwd == NULL)
    2619           0 :         return STATUS_EOF;      /* client wouldn't send password */
    2620             : 
    2621          42 :     if (InitializeLDAPConnection(port, &ldap) == STATUS_ERROR)
    2622             :     {
    2623             :         /* Error message already sent */
    2624           0 :         pfree(passwd);
    2625           0 :         return STATUS_ERROR;
    2626             :     }
    2627             : 
    2628          42 :     if (port->hba->ldapbasedn)
    2629             :     {
    2630             :         /*
    2631             :          * First perform an LDAP search to find the DN for the user we are
    2632             :          * trying to log in as.
    2633             :          */
    2634             :         char       *filter;
    2635             :         LDAPMessage *search_message;
    2636             :         LDAPMessage *entry;
    2637          34 :         char       *attributes[] = {LDAP_NO_ATTRS, NULL};
    2638             :         char       *dn;
    2639             :         char       *c;
    2640             :         int         count;
    2641             : 
    2642             :         /*
    2643             :          * Disallow any characters that we would otherwise need to escape,
    2644             :          * since they aren't really reasonable in a username anyway. Allowing
    2645             :          * them would make it possible to inject any kind of custom filters in
    2646             :          * the LDAP filter.
    2647             :          */
    2648         252 :         for (c = port->user_name; *c; c++)
    2649             :         {
    2650         436 :             if (*c == '*' ||
    2651         436 :                 *c == '(' ||
    2652         436 :                 *c == ')' ||
    2653         436 :                 *c == '\\' ||
    2654         218 :                 *c == '/')
    2655             :             {
    2656           0 :                 ereport(LOG,
    2657             :                         (errmsg("invalid character in user name for LDAP authentication")));
    2658           0 :                 ldap_unbind(ldap);
    2659           0 :                 pfree(passwd);
    2660           6 :                 return STATUS_ERROR;
    2661             :             }
    2662             :         }
    2663             : 
    2664             :         /*
    2665             :          * Bind with a pre-defined username/password (if available) for
    2666             :          * searching. If none is specified, this turns into an anonymous bind.
    2667             :          */
    2668          68 :         r = ldap_simple_bind_s(ldap,
    2669          34 :                                port->hba->ldapbinddn ? port->hba->ldapbinddn : "",
    2670          34 :                                port->hba->ldapbindpasswd ? port->hba->ldapbindpasswd : "");
    2671          34 :         if (r != LDAP_SUCCESS)
    2672             :         {
    2673           0 :             ereport(LOG,
    2674             :                     (errmsg("could not perform initial LDAP bind for ldapbinddn \"%s\" on server \"%s\": %s",
    2675             :                             port->hba->ldapbinddn ? port->hba->ldapbinddn : "",
    2676             :                             server_name,
    2677             :                             ldap_err2string(r)),
    2678             :                      errdetail_for_ldap(ldap)));
    2679           0 :             ldap_unbind(ldap);
    2680           0 :             pfree(passwd);
    2681           0 :             return STATUS_ERROR;
    2682             :         }
    2683             : 
    2684             :         /* Build a custom filter or a single attribute filter? */
    2685          34 :         if (port->hba->ldapsearchfilter)
    2686          16 :             filter = FormatSearchFilter(port->hba->ldapsearchfilter, port->user_name);
    2687          18 :         else if (port->hba->ldapsearchattribute)
    2688           6 :             filter = psprintf("(%s=%s)", port->hba->ldapsearchattribute, port->user_name);
    2689             :         else
    2690          12 :             filter = psprintf("(uid=%s)", port->user_name);
    2691             : 
    2692          68 :         r = ldap_search_s(ldap,
    2693          34 :                           port->hba->ldapbasedn,
    2694          34 :                           port->hba->ldapscope,
    2695             :                           filter,
    2696             :                           attributes,
    2697             :                           0,
    2698             :                           &search_message);
    2699             : 
    2700          34 :         if (r != LDAP_SUCCESS)
    2701             :         {
    2702           0 :             ereport(LOG,
    2703             :                     (errmsg("could not search LDAP for filter \"%s\" on server \"%s\": %s",
    2704             :                             filter, server_name, ldap_err2string(r)),
    2705             :                      errdetail_for_ldap(ldap)));
    2706           0 :             ldap_unbind(ldap);
    2707           0 :             pfree(passwd);
    2708           0 :             pfree(filter);
    2709           0 :             return STATUS_ERROR;
    2710             :         }
    2711             : 
    2712          34 :         count = ldap_count_entries(ldap, search_message);
    2713          34 :         if (count != 1)
    2714             :         {
    2715           6 :             if (count == 0)
    2716           6 :                 ereport(LOG,
    2717             :                         (errmsg("LDAP user \"%s\" does not exist", port->user_name),
    2718             :                          errdetail("LDAP search for filter \"%s\" on server \"%s\" returned no entries.",
    2719             :                                    filter, server_name)));
    2720             :             else
    2721           0 :                 ereport(LOG,
    2722             :                         (errmsg("LDAP user \"%s\" is not unique", port->user_name),
    2723             :                          errdetail_plural("LDAP search for filter \"%s\" on server \"%s\" returned %d entry.",
    2724             :                                           "LDAP search for filter \"%s\" on server \"%s\" returned %d entries.",
    2725             :                                           count,
    2726             :                                           filter, server_name, count)));
    2727             : 
    2728           6 :             ldap_unbind(ldap);
    2729           6 :             pfree(passwd);
    2730           6 :             pfree(filter);
    2731           6 :             ldap_msgfree(search_message);
    2732           6 :             return STATUS_ERROR;
    2733             :         }
    2734             : 
    2735          28 :         entry = ldap_first_entry(ldap, search_message);
    2736          28 :         dn = ldap_get_dn(ldap, entry);
    2737          28 :         if (dn == NULL)
    2738             :         {
    2739             :             int         error;
    2740             : 
    2741           0 :             (void) ldap_get_option(ldap, LDAP_OPT_ERROR_NUMBER, &error);
    2742           0 :             ereport(LOG,
    2743             :                     (errmsg("could not get dn for the first entry matching \"%s\" on server \"%s\": %s",
    2744             :                             filter, server_name,
    2745             :                             ldap_err2string(error)),
    2746             :                      errdetail_for_ldap(ldap)));
    2747           0 :             ldap_unbind(ldap);
    2748           0 :             pfree(passwd);
    2749           0 :             pfree(filter);
    2750           0 :             ldap_msgfree(search_message);
    2751           0 :             return STATUS_ERROR;
    2752             :         }
    2753          28 :         fulluser = pstrdup(dn);
    2754             : 
    2755          28 :         pfree(filter);
    2756          28 :         ldap_memfree(dn);
    2757          28 :         ldap_msgfree(search_message);
    2758             : 
    2759             :         /* Unbind and disconnect from the LDAP server */
    2760          28 :         r = ldap_unbind_s(ldap);
    2761          28 :         if (r != LDAP_SUCCESS)
    2762             :         {
    2763           0 :             ereport(LOG,
    2764             :                     (errmsg("could not unbind after searching for user \"%s\" on server \"%s\"",
    2765             :                             fulluser, server_name)));
    2766           0 :             pfree(passwd);
    2767           0 :             pfree(fulluser);
    2768           0 :             return STATUS_ERROR;
    2769             :         }
    2770             : 
    2771             :         /*
    2772             :          * Need to re-initialize the LDAP connection, so that we can bind to
    2773             :          * it with a different username.
    2774             :          */
    2775          28 :         if (InitializeLDAPConnection(port, &ldap) == STATUS_ERROR)
    2776             :         {
    2777           0 :             pfree(passwd);
    2778           0 :             pfree(fulluser);
    2779             : 
    2780             :             /* Error message already sent */
    2781           0 :             return STATUS_ERROR;
    2782             :         }
    2783             :     }
    2784             :     else
    2785          32 :         fulluser = psprintf("%s%s%s",
    2786          16 :                             port->hba->ldapprefix ? port->hba->ldapprefix : "",
    2787             :                             port->user_name,
    2788          16 :                             port->hba->ldapsuffix ? port->hba->ldapsuffix : "");
    2789             : 
    2790          36 :     r = ldap_simple_bind_s(ldap, fulluser, passwd);
    2791             : 
    2792          36 :     if (r != LDAP_SUCCESS)
    2793             :     {
    2794          12 :         ereport(LOG,
    2795             :                 (errmsg("LDAP login failed for user \"%s\" on server \"%s\": %s",
    2796             :                         fulluser, server_name, ldap_err2string(r)),
    2797             :                  errdetail_for_ldap(ldap)));
    2798          12 :         ldap_unbind(ldap);
    2799          12 :         pfree(passwd);
    2800          12 :         pfree(fulluser);
    2801          12 :         return STATUS_ERROR;
    2802             :     }
    2803             : 
    2804          24 :     ldap_unbind(ldap);
    2805          24 :     pfree(passwd);
    2806          24 :     pfree(fulluser);
    2807             : 
    2808          24 :     return STATUS_OK;
    2809             : }
    2810             : 
    2811             : /*
    2812             :  * Add a detail error message text to the current error if one can be
    2813             :  * constructed from the LDAP 'diagnostic message'.
    2814             :  */
    2815             : static int
    2816          12 : errdetail_for_ldap(LDAP *ldap)
    2817             : {
    2818             :     char       *message;
    2819             :     int         rc;
    2820             : 
    2821          12 :     rc = ldap_get_option(ldap, LDAP_OPT_DIAGNOSTIC_MESSAGE, &message);
    2822          12 :     if (rc == LDAP_SUCCESS && message != NULL)
    2823             :     {
    2824           2 :         errdetail("LDAP diagnostics: %s", message);
    2825           2 :         ldap_memfree(message);
    2826             :     }
    2827             : 
    2828          12 :     return 0;
    2829             : }
    2830             : 
    2831             : #endif                          /* USE_LDAP */
    2832             : 
    2833             : 
    2834             : /*----------------------------------------------------------------
    2835             :  * SSL client certificate authentication
    2836             :  *----------------------------------------------------------------
    2837             :  */
    2838             : #ifdef USE_SSL
    2839             : static int
    2840          12 : CheckCertAuth(Port *port)
    2841             : {
    2842          12 :     int         status_check_usermap = STATUS_ERROR;
    2843             : 
    2844             :     Assert(port->ssl);
    2845             : 
    2846             :     /* Make sure we have received a username in the certificate */
    2847          24 :     if (port->peer_cn == NULL ||
    2848          12 :         strlen(port->peer_cn) <= 0)
    2849             :     {
    2850           0 :         ereport(LOG,
    2851             :                 (errmsg("certificate authentication failed for user \"%s\": client certificate contains no user name",
    2852             :                         port->user_name)));
    2853           0 :         return STATUS_ERROR;
    2854             :     }
    2855             : 
    2856             :     /* Just pass the certificate cn to the usermap check */
    2857          12 :     status_check_usermap = check_usermap(port->hba->usermap, port->user_name, port->peer_cn, false);
    2858          12 :     if (status_check_usermap != STATUS_OK)
    2859             :     {
    2860             :         /*
    2861             :          * If clientcert=verify-full was specified and the authentication
    2862             :          * method is other than uaCert, log the reason for rejecting the
    2863             :          * authentication.
    2864             :          */
    2865           4 :         if (port->hba->clientcert == clientCertFull && port->hba->auth_method != uaCert)
    2866             :         {
    2867           2 :             ereport(LOG,
    2868             :                     (errmsg("certificate validation (clientcert=verify-full) failed for user \"%s\": cn mismatch",
    2869             :                             port->user_name)));
    2870             :         }
    2871             :     }
    2872          12 :     return status_check_usermap;
    2873             : }
    2874             : #endif
    2875             : 
    2876             : 
    2877             : /*----------------------------------------------------------------
    2878             :  * RADIUS authentication
    2879             :  *----------------------------------------------------------------
    2880             :  */
    2881             : 
    2882             : /*
    2883             :  * RADIUS authentication is described in RFC2865 (and several others).
    2884             :  */
    2885             : 
    2886             : #define RADIUS_VECTOR_LENGTH 16
    2887             : #define RADIUS_HEADER_LENGTH 20
    2888             : #define RADIUS_MAX_PASSWORD_LENGTH 128
    2889             : 
    2890             : /* Maximum size of a RADIUS packet we will create or accept */
    2891             : #define RADIUS_BUFFER_SIZE 1024
    2892             : 
    2893             : typedef struct
    2894             : {
    2895             :     uint8       attribute;
    2896             :     uint8       length;
    2897             :     uint8       data[FLEXIBLE_ARRAY_MEMBER];
    2898             : } radius_attribute;
    2899             : 
    2900             : typedef struct
    2901             : {
    2902             :     uint8       code;
    2903             :     uint8       id;
    2904             :     uint16      length;
    2905             :     uint8       vector[RADIUS_VECTOR_LENGTH];
    2906             :     /* this is a bit longer than strictly necessary: */
    2907             :     char        pad[RADIUS_BUFFER_SIZE - RADIUS_VECTOR_LENGTH];
    2908             : } radius_packet;
    2909             : 
    2910             : /* RADIUS packet types */
    2911             : #define RADIUS_ACCESS_REQUEST   1
    2912             : #define RADIUS_ACCESS_ACCEPT    2
    2913             : #define RADIUS_ACCESS_REJECT    3
    2914             : 
    2915             : /* RADIUS attributes */
    2916             : #define RADIUS_USER_NAME        1
    2917             : #define RADIUS_PASSWORD         2
    2918             : #define RADIUS_SERVICE_TYPE     6
    2919             : #define RADIUS_NAS_IDENTIFIER   32
    2920             : 
    2921             : /* RADIUS service types */
    2922             : #define RADIUS_AUTHENTICATE_ONLY    8
    2923             : 
    2924             : /* Seconds to wait - XXX: should be in a config variable! */
    2925             : #define RADIUS_TIMEOUT 3
    2926             : 
    2927             : static void
    2928           0 : radius_add_attribute(radius_packet *packet, uint8 type, const unsigned char *data, int len)
    2929             : {
    2930             :     radius_attribute *attr;
    2931             : 
    2932           0 :     if (packet->length + len > RADIUS_BUFFER_SIZE)
    2933             :     {
    2934             :         /*
    2935             :          * With remotely realistic data, this can never happen. But catch it
    2936             :          * just to make sure we don't overrun a buffer. We'll just skip adding
    2937             :          * the broken attribute, which will in the end cause authentication to
    2938             :          * fail.
    2939             :          */
    2940           0 :         elog(WARNING,
    2941             :              "Adding attribute code %d with length %d to radius packet would create oversize packet, ignoring",
    2942             :              type, len);
    2943           0 :         return;
    2944             :     }
    2945             : 
    2946           0 :     attr = (radius_attribute *) ((unsigned char *) packet + packet->length);
    2947           0 :     attr->attribute = type;
    2948           0 :     attr->length = len + 2;      /* total size includes type and length */
    2949           0 :     memcpy(attr->data, data, len);
    2950           0 :     packet->length += attr->length;
    2951             : }
    2952             : 
    2953             : static int
    2954           0 : CheckRADIUSAuth(Port *port)
    2955             : {
    2956             :     char       *passwd;
    2957             :     ListCell   *server,
    2958             :                *secrets,
    2959             :                *radiusports,
    2960             :                *identifiers;
    2961             : 
    2962             :     /* Make sure struct alignment is correct */
    2963             :     Assert(offsetof(radius_packet, vector) == 4);
    2964             : 
    2965             :     /* Verify parameters */
    2966           0 :     if (list_length(port->hba->radiusservers) < 1)
    2967             :     {
    2968           0 :         ereport(LOG,
    2969             :                 (errmsg("RADIUS server not specified")));
    2970           0 :         return STATUS_ERROR;
    2971             :     }
    2972             : 
    2973           0 :     if (list_length(port->hba->radiussecrets) < 1)
    2974             :     {
    2975           0 :         ereport(LOG,
    2976             :                 (errmsg("RADIUS secret not specified")));
    2977           0 :         return STATUS_ERROR;
    2978             :     }
    2979             : 
    2980             :     /* Send regular password request to client, and get the response */
    2981           0 :     sendAuthRequest(port, AUTH_REQ_PASSWORD, NULL, 0);
    2982             : 
    2983           0 :     passwd = recv_password_packet(port);
    2984           0 :     if (passwd == NULL)
    2985           0 :         return STATUS_EOF;      /* client wouldn't send password */
    2986             : 
    2987           0 :     if (strlen(passwd) > RADIUS_MAX_PASSWORD_LENGTH)
    2988             :     {
    2989           0 :         ereport(LOG,
    2990             :                 (errmsg("RADIUS authentication does not support passwords longer than %d characters", RADIUS_MAX_PASSWORD_LENGTH)));
    2991           0 :         pfree(passwd);
    2992           0 :         return STATUS_ERROR;
    2993             :     }
    2994             : 
    2995             :     /*
    2996             :      * Loop over and try each server in order.
    2997             :      */
    2998           0 :     secrets = list_head(port->hba->radiussecrets);
    2999           0 :     radiusports = list_head(port->hba->radiusports);
    3000           0 :     identifiers = list_head(port->hba->radiusidentifiers);
    3001           0 :     foreach(server, port->hba->radiusservers)
    3002             :     {
    3003           0 :         int         ret = PerformRadiusTransaction(lfirst(server),
    3004           0 :                                                    lfirst(secrets),
    3005             :                                                    radiusports ? lfirst(radiusports) : NULL,
    3006             :                                                    identifiers ? lfirst(identifiers) : NULL,
    3007           0 :                                                    port->user_name,
    3008             :                                                    passwd);
    3009             : 
    3010             :         /*------
    3011             :          * STATUS_OK = Login OK
    3012             :          * STATUS_ERROR = Login not OK, but try next server
    3013             :          * STATUS_EOF = Login not OK, and don't try next server
    3014             :          *------
    3015             :          */
    3016           0 :         if (ret == STATUS_OK)
    3017             :         {
    3018           0 :             pfree(passwd);
    3019           0 :             return STATUS_OK;
    3020             :         }
    3021           0 :         else if (ret == STATUS_EOF)
    3022             :         {
    3023           0 :             pfree(passwd);
    3024           0 :             return STATUS_ERROR;
    3025             :         }
    3026             : 
    3027             :         /*
    3028             :          * secret, port and identifiers either have length 0 (use default),
    3029             :          * length 1 (use the same everywhere) or the same length as servers.
    3030             :          * So if the length is >1, we advance one step. In other cases, we
    3031             :          * don't and will then reuse the correct value.
    3032             :          */
    3033           0 :         if (list_length(port->hba->radiussecrets) > 1)
    3034           0 :             secrets = lnext(secrets);
    3035           0 :         if (list_length(port->hba->radiusports) > 1)
    3036           0 :             radiusports = lnext(radiusports);
    3037           0 :         if (list_length(port->hba->radiusidentifiers) > 1)
    3038           0 :             identifiers = lnext(identifiers);
    3039             :     }
    3040             : 
    3041             :     /* No servers left to try, so give up */
    3042           0 :     pfree(passwd);
    3043           0 :     return STATUS_ERROR;
    3044             : }
    3045             : 
    3046             : static int
    3047           0 : PerformRadiusTransaction(const char *server, const char *secret, const char *portstr, const char *identifier, const char *user_name, const char *passwd)
    3048             : {
    3049             :     radius_packet radius_send_pack;
    3050             :     radius_packet radius_recv_pack;
    3051           0 :     radius_packet *packet = &radius_send_pack;
    3052           0 :     radius_packet *receivepacket = &radius_recv_pack;
    3053           0 :     char       *radius_buffer = (char *) &radius_send_pack;
    3054           0 :     char       *receive_buffer = (char *) &radius_recv_pack;
    3055           0 :     int32       service = pg_hton32(RADIUS_AUTHENTICATE_ONLY);
    3056             :     uint8      *cryptvector;
    3057             :     int         encryptedpasswordlen;
    3058             :     uint8       encryptedpassword[RADIUS_MAX_PASSWORD_LENGTH];
    3059             :     uint8      *md5trailer;
    3060             :     int         packetlength;
    3061             :     pgsocket    sock;
    3062             : 
    3063             : #ifdef HAVE_IPV6
    3064             :     struct sockaddr_in6 localaddr;
    3065             :     struct sockaddr_in6 remoteaddr;
    3066             : #else
    3067             :     struct sockaddr_in localaddr;
    3068             :     struct sockaddr_in remoteaddr;
    3069             : #endif
    3070             :     struct addrinfo hint;
    3071             :     struct addrinfo *serveraddrs;
    3072             :     int         port;
    3073             :     ACCEPT_TYPE_ARG3 addrsize;
    3074             :     fd_set      fdset;
    3075             :     struct timeval endtime;
    3076             :     int         i,
    3077             :                 j,
    3078             :                 r;
    3079             : 
    3080             :     /* Assign default values */
    3081           0 :     if (portstr == NULL)
    3082           0 :         portstr = "1812";
    3083           0 :     if (identifier == NULL)
    3084           0 :         identifier = "postgresql";
    3085             : 
    3086           0 :     MemSet(&hint, 0, sizeof(hint));
    3087           0 :     hint.ai_socktype = SOCK_DGRAM;
    3088           0 :     hint.ai_family = AF_UNSPEC;
    3089           0 :     port = atoi(portstr);
    3090             : 
    3091           0 :     r = pg_getaddrinfo_all(server, portstr, &hint, &serveraddrs);
    3092           0 :     if (r || !serveraddrs)
    3093             :     {
    3094           0 :         ereport(LOG,
    3095             :                 (errmsg("could not translate RADIUS server name \"%s\" to address: %s",
    3096             :                         server, gai_strerror(r))));
    3097           0 :         if (serveraddrs)
    3098           0 :             pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
    3099           0 :         return STATUS_ERROR;
    3100             :     }
    3101             :     /* XXX: add support for multiple returned addresses? */
    3102             : 
    3103             :     /* Construct RADIUS packet */
    3104           0 :     packet->code = RADIUS_ACCESS_REQUEST;
    3105           0 :     packet->length = RADIUS_HEADER_LENGTH;
    3106           0 :     if (!pg_strong_random(packet->vector, RADIUS_VECTOR_LENGTH))
    3107             :     {
    3108           0 :         ereport(LOG,
    3109             :                 (errmsg("could not generate random encryption vector")));
    3110           0 :         pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
    3111           0 :         return STATUS_ERROR;
    3112             :     }
    3113           0 :     packet->id = packet->vector[0];
    3114           0 :     radius_add_attribute(packet, RADIUS_SERVICE_TYPE, (const unsigned char *) &service, sizeof(service));
    3115           0 :     radius_add_attribute(packet, RADIUS_USER_NAME, (const unsigned char *) user_name, strlen(user_name));
    3116           0 :     radius_add_attribute(packet, RADIUS_NAS_IDENTIFIER, (const unsigned char *) identifier, strlen(identifier));
    3117             : 
    3118             :     /*
    3119             :      * RADIUS password attributes are calculated as: e[0] = p[0] XOR
    3120             :      * MD5(secret + Request Authenticator) for the first group of 16 octets,
    3121             :      * and then: e[i] = p[i] XOR MD5(secret + e[i-1]) for the following ones
    3122             :      * (if necessary)
    3123             :      */
    3124           0 :     encryptedpasswordlen = ((strlen(passwd) + RADIUS_VECTOR_LENGTH - 1) / RADIUS_VECTOR_LENGTH) * RADIUS_VECTOR_LENGTH;
    3125           0 :     cryptvector = palloc(strlen(secret) + RADIUS_VECTOR_LENGTH);
    3126           0 :     memcpy(cryptvector, secret, strlen(secret));
    3127             : 
    3128             :     /* for the first iteration, we use the Request Authenticator vector */
    3129           0 :     md5trailer = packet->vector;
    3130           0 :     for (i = 0; i < encryptedpasswordlen; i += RADIUS_VECTOR_LENGTH)
    3131             :     {
    3132           0 :         memcpy(cryptvector + strlen(secret), md5trailer, RADIUS_VECTOR_LENGTH);
    3133             : 
    3134             :         /*
    3135             :          * .. and for subsequent iterations the result of the previous XOR
    3136             :          * (calculated below)
    3137             :          */
    3138           0 :         md5trailer = encryptedpassword + i;
    3139             : 
    3140           0 :         if (!pg_md5_binary(cryptvector, strlen(secret) + RADIUS_VECTOR_LENGTH, encryptedpassword + i))
    3141             :         {
    3142           0 :             ereport(LOG,
    3143             :                     (errmsg("could not perform MD5 encryption of password")));
    3144           0 :             pfree(cryptvector);
    3145           0 :             pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
    3146           0 :             return STATUS_ERROR;
    3147             :         }
    3148             : 
    3149           0 :         for (j = i; j < i + RADIUS_VECTOR_LENGTH; j++)
    3150             :         {
    3151           0 :             if (j < strlen(passwd))
    3152           0 :                 encryptedpassword[j] = passwd[j] ^ encryptedpassword[j];
    3153             :             else
    3154           0 :                 encryptedpassword[j] = '\0' ^ encryptedpassword[j];
    3155             :         }
    3156             :     }
    3157           0 :     pfree(cryptvector);
    3158             : 
    3159           0 :     radius_add_attribute(packet, RADIUS_PASSWORD, encryptedpassword, encryptedpasswordlen);
    3160             : 
    3161             :     /* Length needs to be in network order on the wire */
    3162           0 :     packetlength = packet->length;
    3163           0 :     packet->length = pg_hton16(packet->length);
    3164             : 
    3165           0 :     sock = socket(serveraddrs[0].ai_family, SOCK_DGRAM, 0);
    3166           0 :     if (sock == PGINVALID_SOCKET)
    3167             :     {
    3168           0 :         ereport(LOG,
    3169             :                 (errmsg("could not create RADIUS socket: %m")));
    3170           0 :         pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
    3171           0 :         return STATUS_ERROR;
    3172             :     }
    3173             : 
    3174           0 :     memset(&localaddr, 0, sizeof(localaddr));
    3175             : #ifdef HAVE_IPV6
    3176           0 :     localaddr.sin6_family = serveraddrs[0].ai_family;
    3177           0 :     localaddr.sin6_addr = in6addr_any;
    3178           0 :     if (localaddr.sin6_family == AF_INET6)
    3179           0 :         addrsize = sizeof(struct sockaddr_in6);
    3180             :     else
    3181           0 :         addrsize = sizeof(struct sockaddr_in);
    3182             : #else
    3183             :     localaddr.sin_family = serveraddrs[0].ai_family;
    3184             :     localaddr.sin_addr.s_addr = INADDR_ANY;
    3185             :     addrsize = sizeof(struct sockaddr_in);
    3186             : #endif
    3187             : 
    3188           0 :     if (bind(sock, (struct sockaddr *) &localaddr, addrsize))
    3189             :     {
    3190           0 :         ereport(LOG,
    3191             :                 (errmsg("could not bind local RADIUS socket: %m")));
    3192           0 :         closesocket(sock);
    3193           0 :         pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
    3194           0 :         return STATUS_ERROR;
    3195             :     }
    3196             : 
    3197           0 :     if (sendto(sock, radius_buffer, packetlength, 0,
    3198           0 :                serveraddrs[0].ai_addr, serveraddrs[0].ai_addrlen) < 0)
    3199             :     {
    3200           0 :         ereport(LOG,
    3201             :                 (errmsg("could not send RADIUS packet: %m")));
    3202           0 :         closesocket(sock);
    3203           0 :         pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
    3204           0 :         return STATUS_ERROR;
    3205             :     }
    3206             : 
    3207             :     /* Don't need the server address anymore */
    3208           0 :     pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
    3209             : 
    3210             :     /*
    3211             :      * Figure out at what time we should time out. We can't just use a single
    3212             :      * call to select() with a timeout, since somebody can be sending invalid
    3213             :      * packets to our port thus causing us to retry in a loop and never time
    3214             :      * out.
    3215             :      *
    3216             :      * XXX: Using WaitLatchOrSocket() and doing a CHECK_FOR_INTERRUPTS() if
    3217             :      * the latch was set would improve the responsiveness to
    3218             :      * timeouts/cancellations.
    3219             :      */
    3220           0 :     gettimeofday(&endtime, NULL);
    3221           0 :     endtime.tv_sec += RADIUS_TIMEOUT;
    3222             : 
    3223             :     while (true)
    3224           0 :     {
    3225             :         struct timeval timeout;
    3226             :         struct timeval now;
    3227             :         int64       timeoutval;
    3228             : 
    3229           0 :         gettimeofday(&now, NULL);
    3230           0 :         timeoutval = (endtime.tv_sec * 1000000 + endtime.tv_usec) - (now.tv_sec * 1000000 + now.tv_usec);
    3231           0 :         if (timeoutval <= 0)
    3232             :         {
    3233           0 :             ereport(LOG,
    3234             :                     (errmsg("timeout waiting for RADIUS response from %s",
    3235             :                             server)));
    3236           0 :             closesocket(sock);
    3237           0 :             return STATUS_ERROR;
    3238             :         }
    3239           0 :         timeout.tv_sec = timeoutval / 1000000;
    3240           0 :         timeout.tv_usec = timeoutval % 1000000;
    3241             : 
    3242           0 :         FD_ZERO(&fdset);
    3243           0 :         FD_SET(sock, &fdset);
    3244             : 
    3245           0 :         r = select(sock + 1, &fdset, NULL, NULL, &timeout);
    3246           0 :         if (r < 0)
    3247             :         {
    3248           0 :             if (errno == EINTR)
    3249           0 :                 continue;
    3250             : 
    3251             :             /* Anything else is an actual error */
    3252           0 :             ereport(LOG,
    3253             :                     (errmsg("could not check status on RADIUS socket: %m")));
    3254           0 :             closesocket(sock);
    3255           0 :             return STATUS_ERROR;
    3256             :         }
    3257           0 :         if (r == 0)
    3258             :         {
    3259           0 :             ereport(LOG,
    3260             :                     (errmsg("timeout waiting for RADIUS response from %s",
    3261             :                             server)));
    3262           0 :             closesocket(sock);
    3263           0 :             return STATUS_ERROR;
    3264             :         }
    3265             : 
    3266             :         /*
    3267             :          * Attempt to read the response packet, and verify the contents.
    3268             :          *
    3269             :          * Any packet that's not actually a RADIUS packet, or otherwise does
    3270             :          * not validate as an explicit reject, is just ignored and we retry
    3271             :          * for another packet (until we reach the timeout). This is to avoid
    3272             :          * the possibility to denial-of-service the login by flooding the
    3273             :          * server with invalid packets on the port that we're expecting the
    3274             :          * RADIUS response on.
    3275             :          */
    3276             : 
    3277           0 :         addrsize = sizeof(remoteaddr);
    3278           0 :         packetlength = recvfrom(sock, receive_buffer, RADIUS_BUFFER_SIZE, 0,
    3279             :                                 (struct sockaddr *) &remoteaddr, &addrsize);
    3280           0 :         if (packetlength < 0)
    3281             :         {
    3282           0 :             ereport(LOG,
    3283             :                     (errmsg("could not read RADIUS response: %m")));
    3284           0 :             closesocket(sock);
    3285           0 :             return STATUS_ERROR;
    3286             :         }
    3287             : 
    3288             : #ifdef HAVE_IPV6
    3289           0 :         if (remoteaddr.sin6_port != pg_hton16(port))
    3290             : #else
    3291             :         if (remoteaddr.sin_port != pg_hton16(port))
    3292             : #endif
    3293             :         {
    3294             : #ifdef HAVE_IPV6
    3295           0 :             ereport(LOG,
    3296             :                     (errmsg("RADIUS response from %s was sent from incorrect port: %d",
    3297             :                             server, pg_ntoh16(remoteaddr.sin6_port))));
    3298             : #else
    3299             :             ereport(LOG,
    3300             :                     (errmsg("RADIUS response from %s was sent from incorrect port: %d",
    3301             :                             server, pg_ntoh16(remoteaddr.sin_port))));
    3302             : #endif
    3303           0 :             continue;
    3304             :         }
    3305             : 
    3306           0 :         if (packetlength < RADIUS_HEADER_LENGTH)
    3307             :         {
    3308           0 :             ereport(LOG,
    3309             :                     (errmsg("RADIUS response from %s too short: %d", server, packetlength)));
    3310           0 :             continue;
    3311             :         }
    3312             : 
    3313           0 :         if (packetlength != pg_ntoh16(receivepacket->length))
    3314             :         {
    3315           0 :             ereport(LOG,
    3316             :                     (errmsg("RADIUS response from %s has corrupt length: %d (actual length %d)",
    3317             :                             server, pg_ntoh16(receivepacket->length), packetlength)));
    3318           0 :             continue;
    3319             :         }
    3320             : 
    3321           0 :         if (packet->id != receivepacket->id)
    3322             :         {
    3323           0 :             ereport(LOG,
    3324             :                     (errmsg("RADIUS response from %s is to a different request: %d (should be %d)",
    3325             :                             server, receivepacket->id, packet->id)));
    3326           0 :             continue;
    3327             :         }
    3328             : 
    3329             :         /*
    3330             :          * Verify the response authenticator, which is calculated as
    3331             :          * MD5(Code+ID+Length+RequestAuthenticator+Attributes+Secret)
    3332             :          */
    3333           0 :         cryptvector = palloc(packetlength + strlen(secret));
    3334             : 
    3335           0 :         memcpy(cryptvector, receivepacket, 4);  /* code+id+length */
    3336           0 :         memcpy(cryptvector + 4, packet->vector, RADIUS_VECTOR_LENGTH);   /* request
    3337             :                                                                          * authenticator, from
    3338             :                                                                          * original packet */
    3339           0 :         if (packetlength > RADIUS_HEADER_LENGTH) /* there may be no
    3340             :                                                      * attributes at all */
    3341           0 :             memcpy(cryptvector + RADIUS_HEADER_LENGTH, receive_buffer + RADIUS_HEADER_LENGTH, packetlength - RADIUS_HEADER_LENGTH);
    3342           0 :         memcpy(cryptvector + packetlength, secret, strlen(secret));
    3343             : 
    3344           0 :         if (!pg_md5_binary(cryptvector,
    3345           0 :                            packetlength + strlen(secret),
    3346             :                            encryptedpassword))
    3347             :         {
    3348           0 :             ereport(LOG,
    3349             :                     (errmsg("could not perform MD5 encryption of received packet")));
    3350           0 :             pfree(cryptvector);
    3351           0 :             continue;
    3352             :         }
    3353           0 :         pfree(cryptvector);
    3354             : 
    3355           0 :         if (memcmp(receivepacket->vector, encryptedpassword, RADIUS_VECTOR_LENGTH) != 0)
    3356             :         {
    3357           0 :             ereport(LOG,
    3358             :                     (errmsg("RADIUS response from %s has incorrect MD5 signature",
    3359             :                             server)));
    3360           0 :             continue;
    3361             :         }
    3362             : 
    3363           0 :         if (receivepacket->code == RADIUS_ACCESS_ACCEPT)
    3364             :         {
    3365           0 :             closesocket(sock);
    3366           0 :             return STATUS_OK;
    3367             :         }
    3368           0 :         else if (receivepacket->code == RADIUS_ACCESS_REJECT)
    3369             :         {
    3370           0 :             closesocket(sock);
    3371           0 :             return STATUS_EOF;
    3372             :         }
    3373             :         else
    3374             :         {
    3375           0 :             ereport(LOG,
    3376             :                     (errmsg("RADIUS response from %s has invalid code (%d) for user \"%s\"",
    3377             :                             server, receivepacket->code, user_name)));
    3378           0 :             continue;
    3379             :         }
    3380             :     }                           /* while (true) */
    3381             : }

Generated by: LCOV version 1.13