LCOV - code coverage report
Current view: top level - src/interfaces/libpq - fe-auth.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 61.4 % 376 231
Test Date: 2026-11-23 07:16:20 Functions: 71.4 % 14 10
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 57.4 % 235 135

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * fe-auth.c
       4                 :             :  *     The front-end (client) authorization routines
       5                 :             :  *
       6                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
       7                 :             :  * Portions Copyright (c) 1994, Regents of the University of California
       8                 :             :  *
       9                 :             :  * IDENTIFICATION
      10                 :             :  *    src/interfaces/libpq/fe-auth.c
      11                 :             :  *
      12                 :             :  *-------------------------------------------------------------------------
      13                 :             :  */
      14                 :             : 
      15                 :             : /*
      16                 :             :  * INTERFACE ROUTINES
      17                 :             :  *     frontend (client) routines:
      18                 :             :  *      pg_fe_sendauth          send authentication information
      19                 :             :  *      pg_fe_getauthname       get user's name according to the client side
      20                 :             :  *                              of the authentication system
      21                 :             :  */
      22                 :             : 
      23                 :             : #include "postgres_fe.h"
      24                 :             : 
      25                 :             : #ifdef WIN32
      26                 :             : #include "win32.h"
      27                 :             : #else
      28                 :             : #include <unistd.h>
      29                 :             : #include <fcntl.h>
      30                 :             : #include <limits.h>
      31                 :             : #include <pwd.h>
      32                 :             : #include <sys/param.h>            /* for MAXHOSTNAMELEN on most */
      33                 :             : #include <sys/socket.h>
      34                 :             : #ifdef HAVE_SYS_UCRED_H
      35                 :             : #include <sys/ucred.h>
      36                 :             : #endif
      37                 :             : #ifndef  MAXHOSTNAMELEN
      38                 :             : #include <netdb.h>                /* for MAXHOSTNAMELEN on some */
      39                 :             : #endif
      40                 :             : #endif
      41                 :             : 
      42                 :             : #include "common/md5.h"
      43                 :             : #include "common/oauth-common.h"
      44                 :             : #include "common/scram-common.h"
      45                 :             : #include "fe-auth.h"
      46                 :             : #include "fe-auth-sasl.h"
      47                 :             : #include "fe-auth-oauth.h"
      48                 :             : #include "libpq-fe.h"
      49                 :             : 
      50                 :             : #ifdef ENABLE_GSS
      51                 :             : /*
      52                 :             :  * GSSAPI authentication system.
      53                 :             :  */
      54                 :             : 
      55                 :             : #include "fe-gssapi-common.h"
      56                 :             : 
      57                 :             : /*
      58                 :             :  * Continue GSS authentication with next token as needed.
      59                 :             :  */
      60                 :             : static int
      61                 :             : pg_GSS_continue(PGconn *conn, int payloadlen)
      62                 :             : {
      63                 :             :     OM_uint32   maj_stat,
      64                 :             :                 min_stat,
      65                 :             :                 lmin_s,
      66                 :             :                 gss_flags = GSS_C_MUTUAL_FLAG;
      67                 :             :     gss_buffer_desc ginbuf;
      68                 :             :     gss_buffer_desc goutbuf;
      69                 :             : 
      70                 :             :     /*
      71                 :             :      * On first call, there's no input token. On subsequent calls, read the
      72                 :             :      * input token into a GSS buffer.
      73                 :             :      */
      74                 :             :     if (conn->gctx != GSS_C_NO_CONTEXT)
      75                 :             :     {
      76                 :             :         ginbuf.length = payloadlen;
      77                 :             :         ginbuf.value = malloc(payloadlen);
      78                 :             :         if (!ginbuf.value)
      79                 :             :         {
      80                 :             :             libpq_append_conn_error(conn, "out of memory allocating GSSAPI buffer (%d)",
      81                 :             :                                     payloadlen);
      82                 :             :             return STATUS_ERROR;
      83                 :             :         }
      84                 :             :         if (pqGetnchar(ginbuf.value, payloadlen, conn))
      85                 :             :         {
      86                 :             :             /*
      87                 :             :              * Shouldn't happen, because the caller should've ensured that the
      88                 :             :              * whole message is already in the input buffer.
      89                 :             :              */
      90                 :             :             free(ginbuf.value);
      91                 :             :             return STATUS_ERROR;
      92                 :             :         }
      93                 :             :     }
      94                 :             :     else
      95                 :             :     {
      96                 :             :         ginbuf.length = 0;
      97                 :             :         ginbuf.value = NULL;
      98                 :             :     }
      99                 :             : 
     100                 :             :     /* finished parsing, trace server-to-client message */
     101                 :             :     if (conn->Pfdebug)
     102                 :             :         pqTraceOutputMessage(conn, conn->inBuffer + conn->inStart, false);
     103                 :             : 
     104                 :             :     /* Only try to acquire credentials if GSS delegation isn't disabled. */
     105                 :             :     if (conn->gssdelegation && conn->gssdelegation[0] == '1')
     106                 :             :     {
     107                 :             :         if (conn->gcred == GSS_C_NO_CREDENTIAL)
     108                 :             :             conn->gcred = pg_GSS_get_cred_cache();
     109                 :             :         if (conn->gcred != GSS_C_NO_CREDENTIAL)
     110                 :             :             gss_flags |= GSS_C_DELEG_FLAG;
     111                 :             :     }
     112                 :             : 
     113                 :             :     maj_stat = gss_init_sec_context(&min_stat,
     114                 :             :                                     conn->gcred,
     115                 :             :                                     &conn->gctx,
     116                 :             :                                     conn->gtarg_nam,
     117                 :             :                                     GSS_C_NO_OID,
     118                 :             :                                     gss_flags,
     119                 :             :                                     0,
     120                 :             :                                     GSS_C_NO_CHANNEL_BINDINGS,
     121                 :             :                                     (ginbuf.value == NULL) ? GSS_C_NO_BUFFER : &ginbuf,
     122                 :             :                                     NULL,
     123                 :             :                                     &goutbuf,
     124                 :             :                                     NULL,
     125                 :             :                                     NULL);
     126                 :             : 
     127                 :             :     free(ginbuf.value);
     128                 :             : 
     129                 :             :     if (goutbuf.length != 0)
     130                 :             :     {
     131                 :             :         /*
     132                 :             :          * GSS generated data to send to the server. We don't care if it's the
     133                 :             :          * first or subsequent packet, just send the same kind of password
     134                 :             :          * packet.
     135                 :             :          */
     136                 :             :         conn->current_auth_response = AUTH_RESPONSE_GSS;
     137                 :             :         if (pqPacketSend(conn, PqMsg_GSSResponse,
     138                 :             :                          goutbuf.value, goutbuf.length) != STATUS_OK)
     139                 :             :         {
     140                 :             :             gss_release_buffer(&lmin_s, &goutbuf);
     141                 :             :             return STATUS_ERROR;
     142                 :             :         }
     143                 :             :     }
     144                 :             :     gss_release_buffer(&lmin_s, &goutbuf);
     145                 :             : 
     146                 :             :     if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
     147                 :             :     {
     148                 :             :         pg_GSS_error(libpq_gettext("GSSAPI continuation error"),
     149                 :             :                      conn,
     150                 :             :                      maj_stat, min_stat);
     151                 :             :         gss_release_name(&lmin_s, &conn->gtarg_nam);
     152                 :             :         if (conn->gctx)
     153                 :             :             gss_delete_sec_context(&lmin_s, &conn->gctx, GSS_C_NO_BUFFER);
     154                 :             :         return STATUS_ERROR;
     155                 :             :     }
     156                 :             : 
     157                 :             :     if (maj_stat == GSS_S_COMPLETE)
     158                 :             :     {
     159                 :             :         conn->client_finished_auth = true;
     160                 :             :         gss_release_name(&lmin_s, &conn->gtarg_nam);
     161                 :             :         conn->gssapi_used = true;
     162                 :             :     }
     163                 :             : 
     164                 :             :     return STATUS_OK;
     165                 :             : }
     166                 :             : 
     167                 :             : /*
     168                 :             :  * Send initial GSS authentication token
     169                 :             :  */
     170                 :             : static int
     171                 :             : pg_GSS_startup(PGconn *conn, int payloadlen)
     172                 :             : {
     173                 :             :     int         ret;
     174                 :             :     char       *host = conn->connhost[conn->whichhost].host;
     175                 :             : 
     176                 :             :     if (!(host && host[0] != '\0'))
     177                 :             :     {
     178                 :             :         libpq_append_conn_error(conn, "host name must be specified");
     179                 :             :         return STATUS_ERROR;
     180                 :             :     }
     181                 :             : 
     182                 :             :     if (conn->gctx)
     183                 :             :     {
     184                 :             :         libpq_append_conn_error(conn, "duplicate GSS authentication request");
     185                 :             :         return STATUS_ERROR;
     186                 :             :     }
     187                 :             : 
     188                 :             :     ret = pg_GSS_load_servicename(conn);
     189                 :             :     if (ret != STATUS_OK)
     190                 :             :         return ret;
     191                 :             : 
     192                 :             :     /*
     193                 :             :      * Initial packet is the same as a continuation packet with no initial
     194                 :             :      * context.
     195                 :             :      */
     196                 :             :     conn->gctx = GSS_C_NO_CONTEXT;
     197                 :             : 
     198                 :             :     return pg_GSS_continue(conn, payloadlen);
     199                 :             : }
     200                 :             : #endif                          /* ENABLE_GSS */
     201                 :             : 
     202                 :             : 
     203                 :             : #ifdef ENABLE_SSPI
     204                 :             : /*
     205                 :             :  * SSPI authentication system (Windows only)
     206                 :             :  */
     207                 :             : 
     208                 :             : static void
     209                 :             : pg_SSPI_error(PGconn *conn, const char *mprefix, SECURITY_STATUS r)
     210                 :             : {
     211                 :             :     char        sysmsg[256];
     212                 :             : 
     213                 :             :     if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
     214                 :             :                       FORMAT_MESSAGE_FROM_SYSTEM,
     215                 :             :                       NULL, r, 0,
     216                 :             :                       sysmsg, sizeof(sysmsg), NULL) == 0)
     217                 :             :         appendPQExpBuffer(&conn->errorMessage, "%s: SSPI error %x\n",
     218                 :             :                           mprefix, (unsigned int) r);
     219                 :             :     else
     220                 :             :         appendPQExpBuffer(&conn->errorMessage, "%s: %s (%x)\n",
     221                 :             :                           mprefix, sysmsg, (unsigned int) r);
     222                 :             : }
     223                 :             : 
     224                 :             : /*
     225                 :             :  * Continue SSPI authentication with next token as needed.
     226                 :             :  */
     227                 :             : static int
     228                 :             : pg_SSPI_continue(PGconn *conn, int payloadlen)
     229                 :             : {
     230                 :             :     SECURITY_STATUS r;
     231                 :             :     CtxtHandle  newContext;
     232                 :             :     ULONG       contextAttr;
     233                 :             :     SecBufferDesc inbuf;
     234                 :             :     SecBufferDesc outbuf;
     235                 :             :     SecBuffer   OutBuffers[1];
     236                 :             :     SecBuffer   InBuffers[1];
     237                 :             :     char       *inputbuf = NULL;
     238                 :             : 
     239                 :             :     if (conn->sspictx != NULL)
     240                 :             :     {
     241                 :             :         /*
     242                 :             :          * On runs other than the first we have some data to send. Put this
     243                 :             :          * data in a SecBuffer type structure.
     244                 :             :          */
     245                 :             :         inputbuf = malloc(payloadlen);
     246                 :             :         if (!inputbuf)
     247                 :             :         {
     248                 :             :             libpq_append_conn_error(conn, "out of memory allocating SSPI buffer (%d)",
     249                 :             :                                     payloadlen);
     250                 :             :             return STATUS_ERROR;
     251                 :             :         }
     252                 :             :         if (pqGetnchar(inputbuf, payloadlen, conn))
     253                 :             :         {
     254                 :             :             /*
     255                 :             :              * Shouldn't happen, because the caller should've ensured that the
     256                 :             :              * whole message is already in the input buffer.
     257                 :             :              */
     258                 :             :             free(inputbuf);
     259                 :             :             return STATUS_ERROR;
     260                 :             :         }
     261                 :             : 
     262                 :             :         inbuf.ulVersion = SECBUFFER_VERSION;
     263                 :             :         inbuf.cBuffers = 1;
     264                 :             :         inbuf.pBuffers = InBuffers;
     265                 :             :         InBuffers[0].pvBuffer = inputbuf;
     266                 :             :         InBuffers[0].cbBuffer = payloadlen;
     267                 :             :         InBuffers[0].BufferType = SECBUFFER_TOKEN;
     268                 :             :     }
     269                 :             : 
     270                 :             :     /* finished parsing, trace server-to-client message */
     271                 :             :     if (conn->Pfdebug)
     272                 :             :         pqTraceOutputMessage(conn, conn->inBuffer + conn->inStart, false);
     273                 :             : 
     274                 :             :     OutBuffers[0].pvBuffer = NULL;
     275                 :             :     OutBuffers[0].BufferType = SECBUFFER_TOKEN;
     276                 :             :     OutBuffers[0].cbBuffer = 0;
     277                 :             :     outbuf.cBuffers = 1;
     278                 :             :     outbuf.pBuffers = OutBuffers;
     279                 :             :     outbuf.ulVersion = SECBUFFER_VERSION;
     280                 :             : 
     281                 :             :     r = InitializeSecurityContext(conn->sspicred,
     282                 :             :                                   conn->sspictx,
     283                 :             :                                   conn->sspitarget,
     284                 :             :                                   ISC_REQ_ALLOCATE_MEMORY,
     285                 :             :                                   0,
     286                 :             :                                   SECURITY_NETWORK_DREP,
     287                 :             :                                   (conn->sspictx == NULL) ? NULL : &inbuf,
     288                 :             :                                   0,
     289                 :             :                                   &newContext,
     290                 :             :                                   &outbuf,
     291                 :             :                                   &contextAttr,
     292                 :             :                                   NULL);
     293                 :             : 
     294                 :             :     /* we don't need the input anymore */
     295                 :             :     free(inputbuf);
     296                 :             : 
     297                 :             :     if (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)
     298                 :             :     {
     299                 :             :         pg_SSPI_error(conn, libpq_gettext("SSPI continuation error"), r);
     300                 :             : 
     301                 :             :         return STATUS_ERROR;
     302                 :             :     }
     303                 :             : 
     304                 :             :     if (conn->sspictx == NULL)
     305                 :             :     {
     306                 :             :         /* On first run, transfer retrieved context handle */
     307                 :             :         conn->sspictx = malloc(sizeof(CtxtHandle));
     308                 :             :         if (conn->sspictx == NULL)
     309                 :             :         {
     310                 :             :             libpq_append_conn_error(conn, "out of memory");
     311                 :             :             return STATUS_ERROR;
     312                 :             :         }
     313                 :             :         memcpy(conn->sspictx, &newContext, sizeof(CtxtHandle));
     314                 :             :     }
     315                 :             : 
     316                 :             :     /*
     317                 :             :      * If SSPI returned any data to be sent to the server (as it normally
     318                 :             :      * would), send this data as a password packet.
     319                 :             :      */
     320                 :             :     if (outbuf.cBuffers > 0)
     321                 :             :     {
     322                 :             :         if (outbuf.cBuffers != 1)
     323                 :             :         {
     324                 :             :             /*
     325                 :             :              * This should never happen, at least not for Kerberos
     326                 :             :              * authentication. Keep check in case it shows up with other
     327                 :             :              * authentication methods later.
     328                 :             :              */
     329                 :             :             appendPQExpBufferStr(&conn->errorMessage,
     330                 :             :                                  "SSPI returned invalid number of output buffers\n");
     331                 :             :             return STATUS_ERROR;
     332                 :             :         }
     333                 :             : 
     334                 :             :         /*
     335                 :             :          * If the negotiation is complete, there may be zero bytes to send.
     336                 :             :          * The server is at this point not expecting any more data, so don't
     337                 :             :          * send it.
     338                 :             :          */
     339                 :             :         if (outbuf.pBuffers[0].cbBuffer > 0)
     340                 :             :         {
     341                 :             :             conn->current_auth_response = AUTH_RESPONSE_GSS;
     342                 :             :             if (pqPacketSend(conn, PqMsg_GSSResponse,
     343                 :             :                              outbuf.pBuffers[0].pvBuffer, outbuf.pBuffers[0].cbBuffer))
     344                 :             :             {
     345                 :             :                 FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
     346                 :             :                 return STATUS_ERROR;
     347                 :             :             }
     348                 :             :         }
     349                 :             :         FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
     350                 :             :     }
     351                 :             : 
     352                 :             :     if (r == SEC_E_OK)
     353                 :             :         conn->client_finished_auth = true;
     354                 :             : 
     355                 :             :     /* Cleanup is handled by the code in freePGconn() */
     356                 :             :     return STATUS_OK;
     357                 :             : }
     358                 :             : 
     359                 :             : /*
     360                 :             :  * Send initial SSPI authentication token.
     361                 :             :  * If use_negotiate is 0, use kerberos authentication package which is
     362                 :             :  * compatible with Unix. If use_negotiate is 1, use the negotiate package
     363                 :             :  * which supports both kerberos and NTLM, but is not compatible with Unix.
     364                 :             :  */
     365                 :             : static int
     366                 :             : pg_SSPI_startup(PGconn *conn, int use_negotiate, int payloadlen)
     367                 :             : {
     368                 :             :     SECURITY_STATUS r;
     369                 :             :     TimeStamp   expire;
     370                 :             :     char       *host = conn->connhost[conn->whichhost].host;
     371                 :             : 
     372                 :             :     if (conn->sspictx)
     373                 :             :     {
     374                 :             :         libpq_append_conn_error(conn, "duplicate SSPI authentication request");
     375                 :             :         return STATUS_ERROR;
     376                 :             :     }
     377                 :             : 
     378                 :             :     /*
     379                 :             :      * Retrieve credentials handle
     380                 :             :      */
     381                 :             :     conn->sspicred = malloc(sizeof(CredHandle));
     382                 :             :     if (conn->sspicred == NULL)
     383                 :             :     {
     384                 :             :         libpq_append_conn_error(conn, "out of memory");
     385                 :             :         return STATUS_ERROR;
     386                 :             :     }
     387                 :             : 
     388                 :             :     r = AcquireCredentialsHandle(NULL,
     389                 :             :                                  use_negotiate ? "negotiate" : "kerberos",
     390                 :             :                                  SECPKG_CRED_OUTBOUND,
     391                 :             :                                  NULL,
     392                 :             :                                  NULL,
     393                 :             :                                  NULL,
     394                 :             :                                  NULL,
     395                 :             :                                  conn->sspicred,
     396                 :             :                                  &expire);
     397                 :             :     if (r != SEC_E_OK)
     398                 :             :     {
     399                 :             :         pg_SSPI_error(conn, libpq_gettext("could not acquire SSPI credentials"), r);
     400                 :             :         free(conn->sspicred);
     401                 :             :         conn->sspicred = NULL;
     402                 :             :         return STATUS_ERROR;
     403                 :             :     }
     404                 :             : 
     405                 :             :     /*
     406                 :             :      * Compute target principal name. SSPI has a different format from GSSAPI,
     407                 :             :      * but not more complex. We can skip the @REALM part, because Windows will
     408                 :             :      * fill that in for us automatically.
     409                 :             :      */
     410                 :             :     if (!(host && host[0] != '\0'))
     411                 :             :     {
     412                 :             :         libpq_append_conn_error(conn, "host name must be specified");
     413                 :             :         return STATUS_ERROR;
     414                 :             :     }
     415                 :             :     conn->sspitarget = malloc(strlen(conn->krbsrvname) + strlen(host) + 2);
     416                 :             :     if (!conn->sspitarget)
     417                 :             :     {
     418                 :             :         libpq_append_conn_error(conn, "out of memory");
     419                 :             :         return STATUS_ERROR;
     420                 :             :     }
     421                 :             :     sprintf(conn->sspitarget, "%s/%s", conn->krbsrvname, host);
     422                 :             : 
     423                 :             :     /*
     424                 :             :      * Indicate that we're in SSPI authentication mode to make sure that
     425                 :             :      * pg_SSPI_continue is called next time in the negotiation.
     426                 :             :      */
     427                 :             :     conn->usesspi = 1;
     428                 :             : 
     429                 :             :     return pg_SSPI_continue(conn, payloadlen);
     430                 :             : }
     431                 :             : #endif                          /* ENABLE_SSPI */
     432                 :             : 
     433                 :             : /*
     434                 :             :  * Initialize SASL authentication exchange.
     435                 :             :  */
     436                 :             : static int
     437                 :          75 : pg_SASL_init(PGconn *conn, int payloadlen, bool *async)
     438                 :             : {
     439                 :          75 :     char       *initialresponse = NULL;
     440                 :             :     int         initialresponselen;
     441                 :             :     const char *selected_mechanism;
     442                 :             :     PQExpBufferData mechanism_buf;
     443                 :          75 :     char       *password = NULL;
     444                 :             :     SASLStatus  status;
     445                 :             : 
     446                 :          75 :     initPQExpBuffer(&mechanism_buf);
     447                 :             : 
     448         [ +  + ]:          75 :     if (conn->channel_binding[0] == 'r' &&   /* require */
     449         [ +  + ]:           4 :         !conn->ssl_in_use)
     450                 :             :     {
     451                 :           1 :         libpq_append_conn_error(conn, "channel binding required, but SSL not in use");
     452                 :           1 :         goto error;
     453                 :             :     }
     454                 :             : 
     455   [ -  +  -  - ]:          74 :     if (conn->sasl_state && !conn->async_auth)
     456                 :             :     {
     457                 :           0 :         libpq_append_conn_error(conn, "duplicate SASL authentication request");
     458                 :           0 :         goto error;
     459                 :             :     }
     460                 :             : 
     461                 :             :     /*
     462                 :             :      * Parse the list of SASL authentication mechanisms in the
     463                 :             :      * AuthenticationSASL message, and select the best mechanism that we
     464                 :             :      * support. Mechanisms are listed by order of decreasing importance.
     465                 :             :      */
     466                 :          74 :     selected_mechanism = NULL;
     467                 :             :     for (;;)
     468                 :             :     {
     469         [ -  + ]:         155 :         if (pqGets(&mechanism_buf, conn))
     470                 :             :         {
     471                 :           0 :             appendPQExpBufferStr(&conn->errorMessage,
     472                 :             :                                  "fe_sendauth: invalid authentication request from server: invalid list of authentication mechanisms\n");
     473                 :           0 :             goto error;
     474                 :             :         }
     475         [ -  + ]:         155 :         if (PQExpBufferDataBroken(mechanism_buf))
     476                 :           0 :             goto oom_error;
     477                 :             : 
     478                 :             :         /* An empty string indicates end of list */
     479         [ +  + ]:         155 :         if (mechanism_buf.data[0] == '\0')
     480                 :          74 :             break;
     481                 :             : 
     482                 :             :         /*
     483                 :             :          * Select the mechanism to use.  Pick SCRAM-SHA-256-PLUS over anything
     484                 :             :          * else if a channel binding type is set and if the client supports it
     485                 :             :          * (and did not set channel_binding=disable). Pick SCRAM-SHA-256 if
     486                 :             :          * nothing else has already been picked.  If we add more mechanisms, a
     487                 :             :          * more refined priority mechanism might become necessary.
     488                 :             :          */
     489         [ +  + ]:          81 :         if (strcmp(mechanism_buf.data, SCRAM_SHA_256_PLUS_NAME) == 0)
     490                 :             :         {
     491         [ +  - ]:           7 :             if (conn->ssl_in_use)
     492                 :             :             {
     493                 :             :                 /* The server has offered SCRAM-SHA-256-PLUS. */
     494                 :             : 
     495                 :             : #ifdef USE_SSL
     496                 :             :                 /*
     497                 :             :                  * The client supports channel binding, which is chosen if
     498                 :             :                  * channel_binding is not disabled.
     499                 :             :                  */
     500         [ +  + ]:           7 :                 if (conn->channel_binding[0] != 'd') /* disable */
     501                 :             :                 {
     502                 :           5 :                     selected_mechanism = SCRAM_SHA_256_PLUS_NAME;
     503                 :           5 :                     conn->sasl = &pg_scram_mech;
     504                 :           5 :                     conn->password_needed = true;
     505                 :             :                 }
     506                 :             : #else
     507                 :             :                 /*
     508                 :             :                  * The client does not support channel binding.  If it is
     509                 :             :                  * required, complain immediately instead of the error below
     510                 :             :                  * which would be confusing as the server is publishing
     511                 :             :                  * SCRAM-SHA-256-PLUS.
     512                 :             :                  */
     513                 :             :                 if (conn->channel_binding[0] == 'r') /* require */
     514                 :             :                 {
     515                 :             :                     libpq_append_conn_error(conn, "channel binding is required, but client does not support it");
     516                 :             :                     goto error;
     517                 :             :                 }
     518                 :             : #endif
     519                 :             :             }
     520                 :             :             else
     521                 :             :             {
     522                 :             :                 /*
     523                 :             :                  * The server offered SCRAM-SHA-256-PLUS, but the connection
     524                 :             :                  * is not SSL-encrypted. That's not sane. Perhaps SSL was
     525                 :             :                  * stripped by a proxy? There's no point in continuing,
     526                 :             :                  * because the server will reject the connection anyway if we
     527                 :             :                  * try authenticate without channel binding even though both
     528                 :             :                  * the client and server supported it. The SCRAM exchange
     529                 :             :                  * checks for that, to prevent downgrade attacks.
     530                 :             :                  */
     531                 :           0 :                 libpq_append_conn_error(conn, "server offered SCRAM-SHA-256-PLUS authentication over a non-SSL connection");
     532                 :           0 :                 goto error;
     533                 :             :             }
     534                 :             :         }
     535   [ +  -  +  + ]:          74 :         else if (strcmp(mechanism_buf.data, SCRAM_SHA_256_NAME) == 0 &&
     536                 :             :                  !selected_mechanism)
     537                 :             :         {
     538                 :          69 :             selected_mechanism = SCRAM_SHA_256_NAME;
     539                 :          69 :             conn->sasl = &pg_scram_mech;
     540                 :          69 :             conn->password_needed = true;
     541                 :             :         }
     542   [ -  +  -  - ]:           5 :         else if (strcmp(mechanism_buf.data, OAUTHBEARER_NAME) == 0 &&
     543                 :             :                  !selected_mechanism)
     544                 :             :         {
     545                 :           0 :             selected_mechanism = OAUTHBEARER_NAME;
     546                 :           0 :             conn->sasl = &pg_oauth_mech;
     547                 :           0 :             conn->password_needed = false;
     548                 :             :         }
     549                 :             :     }
     550                 :             : 
     551         [ -  + ]:          74 :     if (!selected_mechanism)
     552                 :             :     {
     553                 :           0 :         libpq_append_conn_error(conn, "none of the server's SASL authentication mechanisms are supported");
     554                 :           0 :         goto error;
     555                 :             :     }
     556                 :             : 
     557                 :             :     /* Make sure require_auth is satisfied. */
     558         [ +  + ]:          74 :     if (conn->require_auth)
     559                 :             :     {
     560                 :          18 :         bool        allowed = false;
     561                 :             : 
     562         [ +  + ]:          26 :         for (size_t i = 0; i < lengthof(conn->allowed_sasl_mechs); i++)
     563                 :             :         {
     564         [ +  + ]:          22 :             if (conn->sasl == conn->allowed_sasl_mechs[i])
     565                 :             :             {
     566                 :          14 :                 allowed = true;
     567                 :          14 :                 break;
     568                 :             :             }
     569                 :             :         }
     570                 :             : 
     571         [ +  + ]:          18 :         if (!allowed)
     572                 :             :         {
     573                 :           4 :             libpq_append_conn_error(conn, "authentication method requirement \"%s\" failed: server requested %s authentication",
     574                 :             :                                     conn->require_auth, selected_mechanism);
     575                 :           4 :             goto error;
     576                 :             :         }
     577                 :             :     }
     578                 :             : 
     579         [ +  + ]:          70 :     if (conn->channel_binding[0] == 'r' &&   /* require */
     580         [ -  + ]:           3 :         strcmp(selected_mechanism, SCRAM_SHA_256_PLUS_NAME) != 0)
     581                 :             :     {
     582                 :           0 :         libpq_append_conn_error(conn, "channel binding is required, but server did not offer an authentication method that supports channel binding");
     583                 :           0 :         goto error;
     584                 :             :     }
     585                 :             : 
     586                 :             :     /*
     587                 :             :      * Now that the SASL mechanism has been chosen for the exchange,
     588                 :             :      * initialize its state information.
     589                 :             :      */
     590                 :             : 
     591                 :             :     /*
     592                 :             :      * First, select the password to use for the exchange, complaining if
     593                 :             :      * there isn't one and the selected SASL mechanism needs it.
     594                 :             :      */
     595   [ +  -  +  + ]:          70 :     if (conn->password_needed && !conn->scram_client_key_binary)
     596                 :             :     {
     597                 :          64 :         password = conn->connhost[conn->whichhost].password;
     598         [ +  - ]:          64 :         if (password == NULL)
     599                 :          64 :             password = conn->pgpass;
     600   [ +  -  -  + ]:          64 :         if (password == NULL || password[0] == '\0')
     601                 :             :         {
     602                 :           0 :             appendPQExpBufferStr(&conn->errorMessage,
     603                 :             :                                  PQnoPasswordSupplied);
     604                 :           0 :             goto error;
     605                 :             :         }
     606                 :             :     }
     607                 :             : 
     608                 :             :     /* finished parsing, trace server-to-client message */
     609         [ -  + ]:          70 :     if (conn->Pfdebug)
     610                 :           0 :         pqTraceOutputMessage(conn, conn->inBuffer + conn->inStart, false);
     611                 :             : 
     612                 :             :     Assert(conn->sasl);
     613                 :             : 
     614         [ +  - ]:          70 :     if (!conn->sasl_state)
     615                 :             :     {
     616                 :             :         /*
     617                 :             :          * Initialize the SASL state information with all the information
     618                 :             :          * gathered during the initial exchange.
     619                 :             :          *
     620                 :             :          * Note: Only tls-unique is supported for the moment.
     621                 :             :          */
     622                 :          70 :         conn->sasl_state = conn->sasl->init(conn,
     623                 :             :                                             password,
     624                 :             :                                             selected_mechanism);
     625         [ -  + ]:          70 :         if (!conn->sasl_state)
     626                 :           0 :             goto oom_error;
     627                 :             :     }
     628                 :             :     else
     629                 :             :     {
     630                 :             :         /*
     631                 :             :          * This is only possible if we're returning from an async loop.
     632                 :             :          * Disconnect it now.
     633                 :             :          */
     634                 :             :         Assert(conn->async_auth);
     635                 :           0 :         conn->async_auth = NULL;
     636                 :             :     }
     637                 :             : 
     638                 :             :     /* Get the mechanism-specific Initial Client Response, if any */
     639                 :          70 :     status = conn->sasl->exchange(conn->sasl_state, false,
     640                 :             :                                   NULL, -1,
     641                 :             :                                   &initialresponse, &initialresponselen);
     642                 :             : 
     643         [ -  + ]:          70 :     if (status == SASL_FAILED)
     644                 :           0 :         goto error;
     645                 :             : 
     646         [ -  + ]:          70 :     if (status == SASL_ASYNC)
     647                 :             :     {
     648                 :             :         /*
     649                 :             :          * The mechanism should have set up the necessary callbacks; all we
     650                 :             :          * need to do is signal the caller.
     651                 :             :          *
     652                 :             :          * In non-assertion builds, this postcondition is enforced at time of
     653                 :             :          * use in PQconnectPoll().
     654                 :             :          */
     655                 :             :         Assert(conn->async_auth);
     656                 :             :         Assert(conn->cleanup_async_auth);
     657                 :             : 
     658                 :           0 :         *async = true;
     659                 :           0 :         return STATUS_OK;
     660                 :             :     }
     661                 :             : 
     662                 :             :     /*
     663                 :             :      * Build a SASLInitialResponse message, and send it.
     664                 :             :      */
     665         [ -  + ]:          70 :     if (pqPutMsgStart(PqMsg_SASLInitialResponse, conn))
     666                 :           0 :         goto error;
     667         [ -  + ]:          70 :     if (pqPuts(selected_mechanism, conn))
     668                 :           0 :         goto error;
     669         [ +  - ]:          70 :     if (initialresponse)
     670                 :             :     {
     671         [ -  + ]:          70 :         if (pqPutInt(initialresponselen, 4, conn))
     672                 :           0 :             goto error;
     673         [ -  + ]:          70 :         if (pqPutnchar(initialresponse, initialresponselen, conn))
     674                 :           0 :             goto error;
     675                 :             :     }
     676                 :          70 :     conn->current_auth_response = AUTH_RESPONSE_SASL_INITIAL;
     677         [ -  + ]:          70 :     if (pqPutMsgEnd(conn))
     678                 :           0 :         goto error;
     679                 :             : 
     680         [ -  + ]:          70 :     if (pqFlush(conn))
     681                 :           0 :         goto error;
     682                 :             : 
     683                 :          70 :     termPQExpBuffer(&mechanism_buf);
     684                 :          70 :     free(initialresponse);
     685                 :             : 
     686                 :          70 :     return STATUS_OK;
     687                 :             : 
     688                 :           5 : error:
     689                 :           5 :     termPQExpBuffer(&mechanism_buf);
     690                 :           5 :     free(initialresponse);
     691                 :           5 :     return STATUS_ERROR;
     692                 :             : 
     693                 :           0 : oom_error:
     694                 :           0 :     termPQExpBuffer(&mechanism_buf);
     695                 :           0 :     free(initialresponse);
     696                 :           0 :     libpq_append_conn_error(conn, "out of memory");
     697                 :           0 :     return STATUS_ERROR;
     698                 :             : }
     699                 :             : 
     700                 :             : /*
     701                 :             :  * Exchange a message for SASL communication protocol with the backend.
     702                 :             :  * This should be used after calling pg_SASL_init to set up the status of
     703                 :             :  * the protocol.
     704                 :             :  */
     705                 :             : static int
     706                 :         133 : pg_SASL_continue(PGconn *conn, int payloadlen, bool final, bool *async)
     707                 :             : {
     708                 :             :     char       *output;
     709                 :             :     int         outputlen;
     710                 :             :     int         res;
     711                 :             :     char       *challenge;
     712                 :             :     SASLStatus  status;
     713                 :             : 
     714                 :             :     /* Read the SASL challenge from the AuthenticationSASLContinue message. */
     715                 :         133 :     challenge = malloc(payloadlen + 1);
     716         [ -  + ]:         133 :     if (!challenge)
     717                 :             :     {
     718                 :           0 :         libpq_append_conn_error(conn, "out of memory allocating SASL buffer (%d)",
     719                 :             :                                 payloadlen);
     720                 :           0 :         return STATUS_ERROR;
     721                 :             :     }
     722                 :             : 
     723         [ -  + ]:         133 :     if (pqGetnchar(challenge, payloadlen, conn))
     724                 :             :     {
     725                 :           0 :         free(challenge);
     726                 :           0 :         return STATUS_ERROR;
     727                 :             :     }
     728                 :             : 
     729                 :             :     /* finished parsing, trace server-to-client message */
     730         [ -  + ]:         133 :     if (conn->Pfdebug)
     731                 :           0 :         pqTraceOutputMessage(conn, conn->inBuffer + conn->inStart, false);
     732                 :             : 
     733                 :             :     /* For safety and convenience, ensure the buffer is NULL-terminated. */
     734                 :         133 :     challenge[payloadlen] = '\0';
     735                 :             : 
     736                 :         133 :     status = conn->sasl->exchange(conn->sasl_state, final,
     737                 :             :                                   challenge, payloadlen,
     738                 :             :                                   &output, &outputlen);
     739                 :         133 :     free(challenge);            /* don't need the input anymore */
     740                 :             : 
     741         [ -  + ]:         133 :     if (status == SASL_ASYNC)
     742                 :             :     {
     743                 :             :         /*
     744                 :             :          * The mechanism should have set up the necessary callbacks; all we
     745                 :             :          * need to do is signal the caller.
     746                 :             :          */
     747                 :           0 :         *async = true;
     748                 :             : 
     749                 :             :         /*
     750                 :             :          * The mechanism may optionally generate some output to send before
     751                 :             :          * switching over to async auth, so continue onwards.
     752                 :             :          */
     753                 :             :     }
     754                 :             : 
     755   [ +  +  -  + ]:         133 :     if (final && status == SASL_CONTINUE)
     756                 :             :     {
     757         [ #  # ]:           0 :         if (outputlen != 0)
     758                 :           0 :             free(output);
     759                 :             : 
     760                 :           0 :         libpq_append_conn_error(conn, "AuthenticationSASLFinal received from server, but SASL authentication was not completed");
     761                 :           0 :         return STATUS_ERROR;
     762                 :             :     }
     763                 :             : 
     764                 :             :     /*
     765                 :             :      * If the exchange is not completed yet, we need to make sure that the
     766                 :             :      * SASL mechanism has generated a message to send back.
     767                 :             :      */
     768   [ +  +  -  + ]:         133 :     if (output == NULL && status == SASL_CONTINUE)
     769                 :             :     {
     770                 :           0 :         libpq_append_conn_error(conn, "no client response found after SASL exchange success");
     771                 :           0 :         return STATUS_ERROR;
     772                 :             :     }
     773                 :             : 
     774                 :             :     /*
     775                 :             :      * SASL allows zero-length responses, so this check uses "output" and not
     776                 :             :      * "outputlen" to allow the case of an empty message.
     777                 :             :      */
     778         [ +  + ]:         133 :     if (output)
     779                 :             :     {
     780                 :             :         /*
     781                 :             :          * Send the SASL response to the server.
     782                 :             :          */
     783                 :          70 :         conn->current_auth_response = AUTH_RESPONSE_SASL;
     784                 :          70 :         res = pqPacketSend(conn, PqMsg_SASLResponse, output, outputlen);
     785                 :          70 :         free(output);
     786                 :             : 
     787         [ -  + ]:          70 :         if (res != STATUS_OK)
     788                 :           0 :             return STATUS_ERROR;
     789                 :             :     }
     790                 :             : 
     791         [ -  + ]:         133 :     if (status == SASL_FAILED)
     792                 :           0 :         return STATUS_ERROR;
     793                 :             : 
     794                 :         133 :     return STATUS_OK;
     795                 :             : }
     796                 :             : 
     797                 :             : static int
     798                 :          44 : pg_password_sendauth(PGconn *conn, const char *password, AuthRequest areq)
     799                 :             : {
     800                 :             :     int         ret;
     801                 :          44 :     char       *crypt_pwd = NULL;
     802                 :             :     const char *pwd_to_send;
     803                 :             :     uint8       md5Salt[4];
     804                 :             : 
     805                 :             :     /* Read the salt from the AuthenticationMD5Password message. */
     806         [ +  + ]:          44 :     if (areq == AUTH_REQ_MD5)
     807                 :             :     {
     808         [ -  + ]:           2 :         if (pqGetnchar(md5Salt, 4, conn))
     809                 :           0 :             return STATUS_ERROR;    /* shouldn't happen */
     810                 :             :     }
     811                 :             : 
     812                 :             :     /* finished parsing, trace server-to-client message */
     813         [ -  + ]:          44 :     if (conn->Pfdebug)
     814                 :           0 :         pqTraceOutputMessage(conn, conn->inBuffer + conn->inStart, false);
     815                 :             : 
     816                 :             :     /* Encrypt the password if needed. */
     817                 :             : 
     818      [ +  +  - ]:          44 :     switch (areq)
     819                 :             :     {
     820                 :           2 :         case AUTH_REQ_MD5:
     821                 :             :             {
     822                 :             :                 char       *crypt_pwd2;
     823                 :           2 :                 const char *errstr = NULL;
     824                 :             : 
     825                 :             :                 /* Allocate enough space for two MD5 hashes */
     826                 :           2 :                 crypt_pwd = malloc(2 * (MD5_PASSWD_LEN + 1));
     827         [ -  + ]:           2 :                 if (!crypt_pwd)
     828                 :             :                 {
     829                 :           0 :                     libpq_append_conn_error(conn, "out of memory");
     830                 :           0 :                     return STATUS_ERROR;
     831                 :             :                 }
     832                 :             : 
     833                 :           2 :                 crypt_pwd2 = crypt_pwd + MD5_PASSWD_LEN + 1;
     834         [ -  + ]:           2 :                 if (!pg_md5_encrypt(password, (uint8 *) conn->pguser,
     835                 :           2 :                                     strlen(conn->pguser), crypt_pwd2,
     836                 :             :                                     &errstr))
     837                 :             :                 {
     838                 :           0 :                     libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
     839                 :           0 :                     free(crypt_pwd);
     840                 :           0 :                     return STATUS_ERROR;
     841                 :             :                 }
     842         [ -  + ]:           2 :                 if (!pg_md5_encrypt(crypt_pwd2 + strlen("md5"), md5Salt,
     843                 :             :                                     4, crypt_pwd, &errstr))
     844                 :             :                 {
     845                 :           0 :                     libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
     846                 :           0 :                     free(crypt_pwd);
     847                 :           0 :                     return STATUS_ERROR;
     848                 :             :                 }
     849                 :             : 
     850                 :           2 :                 pwd_to_send = crypt_pwd;
     851                 :           2 :                 break;
     852                 :             :             }
     853                 :          42 :         case AUTH_REQ_PASSWORD:
     854                 :          42 :             pwd_to_send = password;
     855                 :          42 :             break;
     856                 :           0 :         default:
     857                 :           0 :             return STATUS_ERROR;
     858                 :             :     }
     859                 :          44 :     conn->current_auth_response = AUTH_RESPONSE_PASSWORD;
     860                 :          44 :     ret = pqPacketSend(conn, PqMsg_PasswordMessage,
     861                 :          44 :                        pwd_to_send, strlen(pwd_to_send) + 1);
     862                 :          44 :     free(crypt_pwd);
     863                 :          44 :     return ret;
     864                 :             : }
     865                 :             : 
     866                 :             : /*
     867                 :             :  * Translate a disallowed AuthRequest code into an error message.
     868                 :             :  */
     869                 :             : static const char *
     870                 :          12 : auth_method_description(AuthRequest areq)
     871                 :             : {
     872   [ +  -  -  -  :          12 :     switch (areq)
                   +  - ]
     873                 :             :     {
     874                 :           6 :         case AUTH_REQ_PASSWORD:
     875                 :           6 :             return libpq_gettext("server requested a cleartext password");
     876                 :           0 :         case AUTH_REQ_MD5:
     877                 :           0 :             return libpq_gettext("server requested a hashed password");
     878                 :           0 :         case AUTH_REQ_GSS:
     879                 :             :         case AUTH_REQ_GSS_CONT:
     880                 :           0 :             return libpq_gettext("server requested GSSAPI authentication");
     881                 :           0 :         case AUTH_REQ_SSPI:
     882                 :           0 :             return libpq_gettext("server requested SSPI authentication");
     883                 :           6 :         case AUTH_REQ_SASL:
     884                 :             :         case AUTH_REQ_SASL_CONT:
     885                 :             :         case AUTH_REQ_SASL_FIN:
     886                 :           6 :             return libpq_gettext("server requested SASL authentication");
     887                 :             :     }
     888                 :             : 
     889                 :           0 :     return libpq_gettext("server requested an unknown authentication type");
     890                 :             : }
     891                 :             : 
     892                 :             : /*
     893                 :             :  * Convenience macro for checking the allowed_auth_methods bitmask.  Caller
     894                 :             :  * must ensure that type is not greater than 31 (high bit of the bitmask).
     895                 :             :  */
     896                 :             : #define auth_method_allowed(conn, type) \
     897                 :             :     (((conn)->allowed_auth_methods & (1 << (type))) != 0)
     898                 :             : 
     899                 :             : /*
     900                 :             :  * Verify that the authentication request is expected, given the connection
     901                 :             :  * parameters. This is especially important when the client wishes to
     902                 :             :  * authenticate the server before any sensitive information is exchanged.
     903                 :             :  */
     904                 :             : static bool
     905                 :       16884 : check_expected_areq(AuthRequest areq, PGconn *conn)
     906                 :             : {
     907                 :       16884 :     bool        result = true;
     908                 :       16884 :     const char *reason = NULL;
     909                 :             : 
     910                 :             :     StaticAssertDecl((sizeof(conn->allowed_auth_methods) * CHAR_BIT) > AUTH_REQ_MAX,
     911                 :             :                      "AUTH_REQ_MAX overflows the allowed_auth_methods bitmask");
     912                 :             : 
     913         [ +  + ]:       16884 :     if (conn->sslcertmode[0] == 'r' /* require */
     914         [ +  - ]:           5 :         && areq == AUTH_REQ_OK)
     915                 :             :     {
     916                 :             :         /*
     917                 :             :          * Trade off a little bit of complexity to try to get these error
     918                 :             :          * messages as precise as possible.
     919                 :             :          */
     920         [ -  + ]:           5 :         if (!conn->ssl_cert_requested)
     921                 :             :         {
     922                 :           0 :             libpq_append_conn_error(conn, "server did not request an SSL certificate");
     923                 :           0 :             return false;
     924                 :             :         }
     925         [ +  + ]:           5 :         else if (!conn->ssl_cert_sent)
     926                 :             :         {
     927                 :           1 :             libpq_append_conn_error(conn, "server accepted connection without a valid SSL certificate");
     928                 :           1 :             return false;
     929                 :             :         }
     930                 :             :     }
     931                 :             : 
     932                 :             :     /*
     933                 :             :      * If the user required a specific auth method, or specified an allowed
     934                 :             :      * set, then reject all others here, and make sure the server actually
     935                 :             :      * completes an authentication exchange.
     936                 :             :      */
     937         [ +  + ]:       16883 :     if (conn->require_auth)
     938                 :             :     {
     939      [ +  +  - ]:          98 :         switch (areq)
     940                 :             :         {
     941                 :          35 :             case AUTH_REQ_OK:
     942                 :             : 
     943                 :             :                 /*
     944                 :             :                  * Check to make sure we've actually finished our exchange (or
     945                 :             :                  * else that the user has allowed an authentication-less
     946                 :             :                  * connection).
     947                 :             :                  *
     948                 :             :                  * If the user has allowed both SCRAM and unauthenticated
     949                 :             :                  * (trust) connections, then this check will silently accept
     950                 :             :                  * partial SCRAM exchanges, where a misbehaving server does
     951                 :             :                  * not provide its verifier before sending an OK.  This is
     952                 :             :                  * consistent with historical behavior, but it may be a point
     953                 :             :                  * to revisit in the future, since it could allow a server
     954                 :             :                  * that doesn't know the user's password to silently harvest
     955                 :             :                  * material for a brute force attack.
     956                 :             :                  */
     957   [ +  +  +  + ]:          35 :                 if (!conn->auth_required || conn->client_finished_auth)
     958                 :             :                     break;
     959                 :             : 
     960                 :             :                 /*
     961                 :             :                  * No explicit authentication request was made by the server
     962                 :             :                  * -- or perhaps it was made and not completed, in the case of
     963                 :             :                  * SCRAM -- but there is one special case to check.  If the
     964                 :             :                  * user allowed "gss", then a GSS-encrypted channel also
     965                 :             :                  * satisfies the check.
     966                 :             :                  */
     967                 :             : #ifdef ENABLE_GSS
     968                 :             :                 if (auth_method_allowed(conn, AUTH_REQ_GSS) && conn->gssenc)
     969                 :             :                 {
     970                 :             :                     /*
     971                 :             :                      * If implicit GSS auth has already been performed via GSS
     972                 :             :                      * encryption, we don't need to have performed an
     973                 :             :                      * AUTH_REQ_GSS exchange.  This allows require_auth=gss to
     974                 :             :                      * be combined with gssencmode, since there won't be an
     975                 :             :                      * explicit authentication request in that case.
     976                 :             :                      */
     977                 :             :                 }
     978                 :             :                 else
     979                 :             : #endif
     980                 :             :                 {
     981                 :           9 :                     reason = libpq_gettext("server did not complete authentication");
     982                 :           9 :                     result = false;
     983                 :             :                 }
     984                 :             : 
     985                 :           9 :                 break;
     986                 :             : 
     987                 :          63 :             case AUTH_REQ_PASSWORD:
     988                 :             :             case AUTH_REQ_MD5:
     989                 :             :             case AUTH_REQ_GSS:
     990                 :             :             case AUTH_REQ_GSS_CONT:
     991                 :             :             case AUTH_REQ_SSPI:
     992                 :             :             case AUTH_REQ_SASL:
     993                 :             :             case AUTH_REQ_SASL_CONT:
     994                 :             :             case AUTH_REQ_SASL_FIN:
     995                 :             : 
     996                 :             :                 /*
     997                 :             :                  * We don't handle these with the default case, to avoid
     998                 :             :                  * bit-shifting past the end of the allowed_auth_methods mask
     999                 :             :                  * if the server sends an unexpected AuthRequest.
    1000                 :             :                  */
    1001                 :          63 :                 result = auth_method_allowed(conn, areq);
    1002                 :          63 :                 break;
    1003                 :             : 
    1004                 :           0 :             default:
    1005                 :           0 :                 result = false;
    1006                 :           0 :                 break;
    1007                 :             :         }
    1008                 :             :     }
    1009                 :             : 
    1010         [ +  + ]:       16883 :     if (!result)
    1011                 :             :     {
    1012         [ +  + ]:          21 :         if (!reason)
    1013                 :          12 :             reason = auth_method_description(areq);
    1014                 :             : 
    1015                 :          21 :         libpq_append_conn_error(conn, "authentication method requirement \"%s\" failed: %s",
    1016                 :             :                                 conn->require_auth, reason);
    1017                 :          21 :         return result;
    1018                 :             :     }
    1019                 :             : 
    1020                 :             :     /*
    1021                 :             :      * When channel_binding=require, we must protect against two cases: (1) we
    1022                 :             :      * must not respond to non-SASL authentication requests, which might leak
    1023                 :             :      * information such as the client's password; and (2) even if we receive
    1024                 :             :      * AUTH_REQ_OK, we still must ensure that channel binding has happened in
    1025                 :             :      * order to authenticate the server.
    1026                 :             :      */
    1027         [ +  + ]:       16862 :     if (conn->channel_binding[0] == 'r' /* require */ )
    1028                 :             :     {
    1029      [ +  +  + ]:          17 :         switch (areq)
    1030                 :             :         {
    1031                 :          10 :             case AUTH_REQ_SASL:
    1032                 :             :             case AUTH_REQ_SASL_CONT:
    1033                 :             :             case AUTH_REQ_SASL_FIN:
    1034                 :          10 :                 break;
    1035                 :           4 :             case AUTH_REQ_OK:
    1036   [ +  +  -  + ]:           4 :                 if (!conn->sasl || !conn->sasl->channel_bound(conn->sasl_state))
    1037                 :             :                 {
    1038                 :           1 :                     libpq_append_conn_error(conn, "channel binding required, but server authenticated client without channel binding");
    1039                 :           1 :                     result = false;
    1040                 :             :                 }
    1041                 :           4 :                 break;
    1042                 :           3 :             default:
    1043                 :           3 :                 libpq_append_conn_error(conn, "channel binding required but not supported by server's authentication request");
    1044                 :           3 :                 result = false;
    1045                 :           3 :                 break;
    1046                 :             :         }
    1047                 :             :     }
    1048                 :             : 
    1049                 :       16862 :     return result;
    1050                 :             : }
    1051                 :             : 
    1052                 :             : /*
    1053                 :             :  * pg_fe_sendauth
    1054                 :             :  *      client demux routine for processing an authentication request
    1055                 :             :  *
    1056                 :             :  * The server has sent us an authentication challenge (or OK). Send an
    1057                 :             :  * appropriate response. The caller has ensured that the whole message is
    1058                 :             :  * now in the input buffer, and has already read the type and length of
    1059                 :             :  * it. We are responsible for reading any remaining extra data, specific
    1060                 :             :  * to the authentication method. 'payloadlen' is the remaining length in
    1061                 :             :  * the message.
    1062                 :             :  *
    1063                 :             :  * If *async is set to true on return, the client doesn't yet have enough
    1064                 :             :  * information to respond, and the caller must temporarily switch to
    1065                 :             :  * conn->async_auth() to continue driving the exchange.
    1066                 :             :  */
    1067                 :             : int
    1068                 :       16884 : pg_fe_sendauth(AuthRequest areq, int payloadlen, PGconn *conn, bool *async)
    1069                 :             : {
    1070                 :             :     int         oldmsglen;
    1071                 :             : 
    1072                 :       16884 :     *async = false;
    1073                 :             : 
    1074         [ +  + ]:       16884 :     if (!check_expected_areq(areq, conn))
    1075                 :          26 :         return STATUS_ERROR;
    1076                 :             : 
    1077   [ +  -  -  -  :       16858 :     switch (areq)
          -  -  +  +  +  
                      - ]
    1078                 :             :     {
    1079                 :       16605 :         case AUTH_REQ_OK:
    1080                 :       16605 :             break;
    1081                 :             : 
    1082                 :           0 :         case AUTH_REQ_KRB4:
    1083                 :           0 :             libpq_append_conn_error(conn, "Kerberos 4 authentication not supported");
    1084                 :           0 :             return STATUS_ERROR;
    1085                 :             : 
    1086                 :           0 :         case AUTH_REQ_KRB5:
    1087                 :           0 :             libpq_append_conn_error(conn, "Kerberos 5 authentication not supported");
    1088                 :           0 :             return STATUS_ERROR;
    1089                 :             : 
    1090                 :             : #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
    1091                 :             :         case AUTH_REQ_GSS:
    1092                 :             : #if !defined(ENABLE_SSPI)
    1093                 :             :             /* no native SSPI, so use GSSAPI library for it */
    1094                 :             :         case AUTH_REQ_SSPI:
    1095                 :             : #endif
    1096                 :             :             {
    1097                 :             :                 int         r;
    1098                 :             : 
    1099                 :             :                 pglock_thread();
    1100                 :             : 
    1101                 :             :                 /*
    1102                 :             :                  * If we have both GSS and SSPI support compiled in, use SSPI
    1103                 :             :                  * support by default. This is overridable by a connection
    1104                 :             :                  * string parameter. Note that when using SSPI we still leave
    1105                 :             :                  * the negotiate parameter off, since we want SSPI to use the
    1106                 :             :                  * GSSAPI kerberos protocol. For actual SSPI negotiate
    1107                 :             :                  * protocol, we use AUTH_REQ_SSPI.
    1108                 :             :                  */
    1109                 :             : #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
    1110                 :             :                 if (conn->gsslib && (pg_strcasecmp(conn->gsslib, "gssapi") == 0))
    1111                 :             :                     r = pg_GSS_startup(conn, payloadlen);
    1112                 :             :                 else
    1113                 :             :                     r = pg_SSPI_startup(conn, 0, payloadlen);
    1114                 :             : #elif defined(ENABLE_GSS) && !defined(ENABLE_SSPI)
    1115                 :             :                 r = pg_GSS_startup(conn, payloadlen);
    1116                 :             : #elif !defined(ENABLE_GSS) && defined(ENABLE_SSPI)
    1117                 :             :                 r = pg_SSPI_startup(conn, 0, payloadlen);
    1118                 :             : #endif
    1119                 :             :                 if (r != STATUS_OK)
    1120                 :             :                 {
    1121                 :             :                     /* Error message already filled in. */
    1122                 :             :                     pgunlock_thread();
    1123                 :             :                     return STATUS_ERROR;
    1124                 :             :                 }
    1125                 :             :                 pgunlock_thread();
    1126                 :             :             }
    1127                 :             :             break;
    1128                 :             : 
    1129                 :             :         case AUTH_REQ_GSS_CONT:
    1130                 :             :             {
    1131                 :             :                 int         r;
    1132                 :             : 
    1133                 :             :                 pglock_thread();
    1134                 :             : #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
    1135                 :             :                 if (conn->usesspi)
    1136                 :             :                     r = pg_SSPI_continue(conn, payloadlen);
    1137                 :             :                 else
    1138                 :             :                     r = pg_GSS_continue(conn, payloadlen);
    1139                 :             : #elif defined(ENABLE_GSS) && !defined(ENABLE_SSPI)
    1140                 :             :                 r = pg_GSS_continue(conn, payloadlen);
    1141                 :             : #elif !defined(ENABLE_GSS) && defined(ENABLE_SSPI)
    1142                 :             :                 r = pg_SSPI_continue(conn, payloadlen);
    1143                 :             : #endif
    1144                 :             :                 if (r != STATUS_OK)
    1145                 :             :                 {
    1146                 :             :                     /* Error message already filled in. */
    1147                 :             :                     pgunlock_thread();
    1148                 :             :                     return STATUS_ERROR;
    1149                 :             :                 }
    1150                 :             :                 pgunlock_thread();
    1151                 :             :             }
    1152                 :             :             break;
    1153                 :             : #else                           /* defined(ENABLE_GSS) || defined(ENABLE_SSPI) */
    1154                 :             :             /* No GSSAPI *or* SSPI support */
    1155                 :           0 :         case AUTH_REQ_GSS:
    1156                 :             :         case AUTH_REQ_GSS_CONT:
    1157                 :           0 :             libpq_append_conn_error(conn, "GSSAPI authentication not supported");
    1158                 :           0 :             return STATUS_ERROR;
    1159                 :             : #endif                          /* defined(ENABLE_GSS) || defined(ENABLE_SSPI) */
    1160                 :             : 
    1161                 :             : #ifdef ENABLE_SSPI
    1162                 :             :         case AUTH_REQ_SSPI:
    1163                 :             : 
    1164                 :             :             /*
    1165                 :             :              * SSPI has its own startup message so libpq can decide which
    1166                 :             :              * method to use. Indicate to pg_SSPI_startup that we want SSPI
    1167                 :             :              * negotiation instead of Kerberos.
    1168                 :             :              */
    1169                 :             :             pglock_thread();
    1170                 :             :             if (pg_SSPI_startup(conn, 1, payloadlen) != STATUS_OK)
    1171                 :             :             {
    1172                 :             :                 /* Error message already filled in. */
    1173                 :             :                 pgunlock_thread();
    1174                 :             :                 return STATUS_ERROR;
    1175                 :             :             }
    1176                 :             :             pgunlock_thread();
    1177                 :             :             break;
    1178                 :             : #else
    1179                 :             : 
    1180                 :             :             /*
    1181                 :             :              * No SSPI support. However, if we have GSSAPI but not SSPI
    1182                 :             :              * support, AUTH_REQ_SSPI will have been handled in the codepath
    1183                 :             :              * for AUTH_REQ_GSS above, so don't duplicate the case label in
    1184                 :             :              * that case.
    1185                 :             :              */
    1186                 :             : #if !defined(ENABLE_GSS)
    1187                 :           0 :         case AUTH_REQ_SSPI:
    1188                 :           0 :             libpq_append_conn_error(conn, "SSPI authentication not supported");
    1189                 :           0 :             return STATUS_ERROR;
    1190                 :             : #endif                          /* !define(ENABLE_GSS) */
    1191                 :             : #endif                          /* ENABLE_SSPI */
    1192                 :             : 
    1193                 :             : 
    1194                 :           0 :         case AUTH_REQ_CRYPT:
    1195                 :           0 :             libpq_append_conn_error(conn, "Crypt authentication not supported");
    1196                 :           0 :             return STATUS_ERROR;
    1197                 :             : 
    1198                 :          45 :         case AUTH_REQ_MD5:
    1199                 :             :         case AUTH_REQ_PASSWORD:
    1200                 :             :             {
    1201                 :             :                 char       *password;
    1202                 :             : 
    1203                 :          45 :                 conn->password_needed = true;
    1204                 :          45 :                 password = conn->connhost[conn->whichhost].password;
    1205         [ +  + ]:          45 :                 if (password == NULL)
    1206                 :          40 :                     password = conn->pgpass;
    1207   [ +  +  -  + ]:          45 :                 if (password == NULL || password[0] == '\0')
    1208                 :             :                 {
    1209                 :           1 :                     appendPQExpBufferStr(&conn->errorMessage,
    1210                 :             :                                          PQnoPasswordSupplied);
    1211                 :           1 :                     return STATUS_ERROR;
    1212                 :             :                 }
    1213         [ -  + ]:          44 :                 if (pg_password_sendauth(conn, password, areq) != STATUS_OK)
    1214                 :             :                 {
    1215                 :           0 :                     appendPQExpBufferStr(&conn->errorMessage,
    1216                 :             :                                          "fe_sendauth: error sending password authentication\n");
    1217                 :           0 :                     return STATUS_ERROR;
    1218                 :             :                 }
    1219                 :             : 
    1220                 :             :                 /* We expect no further authentication requests. */
    1221                 :          44 :                 conn->client_finished_auth = true;
    1222                 :          44 :                 break;
    1223                 :             :             }
    1224                 :             : 
    1225                 :          75 :         case AUTH_REQ_SASL:
    1226                 :             : 
    1227                 :             :             /*
    1228                 :             :              * The request contains the name (as assigned by IANA) of the
    1229                 :             :              * authentication mechanism.
    1230                 :             :              */
    1231         [ +  + ]:          75 :             if (pg_SASL_init(conn, payloadlen, async) != STATUS_OK)
    1232                 :             :             {
    1233                 :             :                 /* pg_SASL_init already set the error message */
    1234                 :           5 :                 return STATUS_ERROR;
    1235                 :             :             }
    1236                 :          70 :             break;
    1237                 :             : 
    1238                 :         133 :         case AUTH_REQ_SASL_CONT:
    1239                 :             :         case AUTH_REQ_SASL_FIN:
    1240                 :             :             {
    1241                 :         133 :                 bool        final = false;
    1242                 :             : 
    1243         [ -  + ]:         133 :                 if (conn->sasl_state == NULL)
    1244                 :             :                 {
    1245                 :           0 :                     appendPQExpBufferStr(&conn->errorMessage,
    1246                 :             :                                          "fe_sendauth: invalid authentication request from server: AUTH_REQ_SASL_CONT without AUTH_REQ_SASL\n");
    1247                 :           0 :                     return STATUS_ERROR;
    1248                 :             :                 }
    1249                 :         133 :                 oldmsglen = conn->errorMessage.len;
    1250                 :             : 
    1251         [ +  + ]:         133 :                 if (areq == AUTH_REQ_SASL_FIN)
    1252                 :          63 :                     final = true;
    1253                 :             : 
    1254         [ -  + ]:         133 :                 if (pg_SASL_continue(conn, payloadlen, final, async) != STATUS_OK)
    1255                 :             :                 {
    1256                 :             :                     /*
    1257                 :             :                      * Append a generic error message unless pg_SASL_continue
    1258                 :             :                      * did set a more specific one already.
    1259                 :             :                      */
    1260         [ #  # ]:           0 :                     if (conn->errorMessage.len == oldmsglen)
    1261                 :           0 :                         appendPQExpBufferStr(&conn->errorMessage,
    1262                 :             :                                              "fe_sendauth: error in SASL authentication\n");
    1263                 :           0 :                     return STATUS_ERROR;
    1264                 :             :                 }
    1265                 :         133 :                 break;
    1266                 :             :             }
    1267                 :             : 
    1268                 :           0 :         default:
    1269                 :           0 :             libpq_append_conn_error(conn, "authentication method %u not supported", areq);
    1270                 :           0 :             return STATUS_ERROR;
    1271                 :             :     }
    1272                 :             : 
    1273                 :       16852 :     return STATUS_OK;
    1274                 :             : }
    1275                 :             : 
    1276                 :             : 
    1277                 :             : /*
    1278                 :             :  * pg_fe_getusername
    1279                 :             :  *
    1280                 :             :  * Returns a pointer to malloc'd space containing the name of the
    1281                 :             :  * specified user_id.  If there is an error, return NULL, and append
    1282                 :             :  * a suitable error message to *errorMessage if that's not NULL.
    1283                 :             :  *
    1284                 :             :  * Caution: on Windows, the user_id argument is ignored, and we always
    1285                 :             :  * fetch the current user's name.
    1286                 :             :  */
    1287                 :             : char *
    1288                 :       15671 : pg_fe_getusername(uid_t user_id, PQExpBuffer errorMessage)
    1289                 :             : {
    1290                 :       15671 :     char       *result = NULL;
    1291                 :       15671 :     const char *name = NULL;
    1292                 :             : 
    1293                 :             : #ifdef WIN32
    1294                 :             :     /* Microsoft recommends buffer size of UNLEN+1, where UNLEN = 256 */
    1295                 :             :     char        username[256 + 1];
    1296                 :             :     DWORD       namesize = sizeof(username);
    1297                 :             : #else
    1298                 :             :     struct passwd pwbuf;
    1299                 :       15671 :     struct passwd *pw = NULL;
    1300                 :             :     char        buf[1024];
    1301                 :             :     int         rc;
    1302                 :             : #endif
    1303                 :             : 
    1304                 :             : #ifdef WIN32
    1305                 :             :     if (GetUserName(username, &namesize))
    1306                 :             :         name = username;
    1307                 :             :     else if (errorMessage)
    1308                 :             :         libpq_append_error(errorMessage,
    1309                 :             :                            "user name lookup failure: error code %lu",
    1310                 :             :                            GetLastError());
    1311                 :             : #else
    1312                 :       15671 :     rc = getpwuid_r(user_id, &pwbuf, buf, sizeof buf, &pw);
    1313         [ -  + ]:       15671 :     if (rc != 0)
    1314                 :             :     {
    1315                 :           0 :         errno = rc;
    1316         [ #  # ]:           0 :         if (errorMessage)
    1317                 :           0 :             libpq_append_error(errorMessage, "could not look up local user ID %ld: %m", (long) user_id);
    1318                 :             :     }
    1319         [ -  + ]:       15671 :     else if (!pw)
    1320                 :             :     {
    1321         [ #  # ]:           0 :         if (errorMessage)
    1322                 :           0 :             libpq_append_error(errorMessage, "local user with ID %ld does not exist", (long) user_id);
    1323                 :             :     }
    1324                 :             :     else
    1325                 :       15671 :         name = pw->pw_name;
    1326                 :             : #endif
    1327                 :             : 
    1328         [ +  - ]:       15671 :     if (name)
    1329                 :             :     {
    1330                 :       15671 :         result = strdup(name);
    1331   [ -  +  -  - ]:       15671 :         if (result == NULL && errorMessage)
    1332                 :           0 :             libpq_append_error(errorMessage, "out of memory");
    1333                 :             :     }
    1334                 :             : 
    1335                 :       15671 :     return result;
    1336                 :             : }
    1337                 :             : 
    1338                 :             : /*
    1339                 :             :  * pg_fe_getauthname
    1340                 :             :  *
    1341                 :             :  * Returns a pointer to malloc'd space containing whatever name the user
    1342                 :             :  * has authenticated to the system.  If there is an error, return NULL,
    1343                 :             :  * and append a suitable error message to *errorMessage if that's not NULL.
    1344                 :             :  */
    1345                 :             : char *
    1346                 :       15671 : pg_fe_getauthname(PQExpBuffer errorMessage)
    1347                 :             : {
    1348                 :             : #ifdef WIN32
    1349                 :             :     return pg_fe_getusername(0, errorMessage);
    1350                 :             : #else
    1351                 :       15671 :     return pg_fe_getusername(geteuid(), errorMessage);
    1352                 :             : #endif
    1353                 :             : }
    1354                 :             : 
    1355                 :             : 
    1356                 :             : /*
    1357                 :             :  * PQencryptPassword -- exported routine to encrypt a password with MD5
    1358                 :             :  *
    1359                 :             :  * This function is equivalent to calling PQencryptPasswordConn with
    1360                 :             :  * "md5" as the encryption method, except that this doesn't require
    1361                 :             :  * a connection object.  This function is deprecated, use
    1362                 :             :  * PQencryptPasswordConn instead.
    1363                 :             :  */
    1364                 :             : char *
    1365                 :           0 : PQencryptPassword(const char *passwd, const char *user)
    1366                 :             : {
    1367                 :             :     char       *crypt_pwd;
    1368                 :           0 :     const char *errstr = NULL;
    1369                 :             : 
    1370                 :           0 :     crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
    1371         [ #  # ]:           0 :     if (!crypt_pwd)
    1372                 :           0 :         return NULL;
    1373                 :             : 
    1374         [ #  # ]:           0 :     if (!pg_md5_encrypt(passwd, (const uint8 *) user, strlen(user), crypt_pwd, &errstr))
    1375                 :             :     {
    1376                 :           0 :         free(crypt_pwd);
    1377                 :           0 :         return NULL;
    1378                 :             :     }
    1379                 :             : 
    1380                 :           0 :     return crypt_pwd;
    1381                 :             : }
    1382                 :             : 
    1383                 :             : /*
    1384                 :             :  * PQencryptPasswordConn -- exported routine to encrypt a password
    1385                 :             :  *
    1386                 :             :  * This is intended to be used by client applications that wish to send
    1387                 :             :  * commands like ALTER USER joe PASSWORD 'pwd'.  The password need not
    1388                 :             :  * be sent in cleartext if it is encrypted on the client side.  This is
    1389                 :             :  * good because it ensures the cleartext password won't end up in logs,
    1390                 :             :  * pg_stat displays, etc.  We export the function so that clients won't
    1391                 :             :  * be dependent on low-level details like whether the encryption is MD5
    1392                 :             :  * or something else.
    1393                 :             :  *
    1394                 :             :  * Arguments are a connection object, the cleartext password, the SQL
    1395                 :             :  * name of the user it is for, and a string indicating the algorithm to
    1396                 :             :  * use for encrypting the password.  If algorithm is NULL, this queries
    1397                 :             :  * the server for the current 'password_encryption' value.  If you wish
    1398                 :             :  * to avoid that, e.g. to avoid blocking, you can execute
    1399                 :             :  * 'show password_encryption' yourself before calling this function, and
    1400                 :             :  * pass it as the algorithm.
    1401                 :             :  *
    1402                 :             :  * Return value is a malloc'd string.  The client may assume the string
    1403                 :             :  * doesn't contain any special characters that would require escaping.
    1404                 :             :  * On error, an error message is stored in the connection object, and
    1405                 :             :  * returns NULL.
    1406                 :             :  */
    1407                 :             : char *
    1408                 :           1 : PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user,
    1409                 :             :                       const char *algorithm)
    1410                 :             : {
    1411                 :             : #define MAX_ALGORITHM_NAME_LEN 50
    1412                 :             :     char        algobuf[MAX_ALGORITHM_NAME_LEN + 1];
    1413                 :           1 :     char       *crypt_pwd = NULL;
    1414                 :             : 
    1415         [ -  + ]:           1 :     if (!conn)
    1416                 :           0 :         return NULL;
    1417                 :             : 
    1418                 :           1 :     pqClearConnErrorState(conn);
    1419                 :             : 
    1420                 :             :     /* If no algorithm was given, ask the server. */
    1421         [ +  - ]:           1 :     if (algorithm == NULL)
    1422                 :             :     {
    1423                 :             :         PGresult   *res;
    1424                 :             :         char       *val;
    1425                 :             : 
    1426                 :           1 :         res = PQexec(conn, "show password_encryption");
    1427         [ -  + ]:           1 :         if (res == NULL)
    1428                 :             :         {
    1429                 :             :             /* PQexec() should've set conn->errorMessage already */
    1430                 :           0 :             return NULL;
    1431                 :             :         }
    1432         [ -  + ]:           1 :         if (PQresultStatus(res) != PGRES_TUPLES_OK)
    1433                 :             :         {
    1434                 :             :             /* PQexec() should've set conn->errorMessage already */
    1435                 :           0 :             PQclear(res);
    1436                 :           0 :             return NULL;
    1437                 :             :         }
    1438   [ +  -  -  + ]:           1 :         if (PQntuples(res) != 1 || PQnfields(res) != 1)
    1439                 :             :         {
    1440                 :           0 :             PQclear(res);
    1441                 :           0 :             libpq_append_conn_error(conn, "unexpected shape of result set returned for SHOW");
    1442                 :           0 :             return NULL;
    1443                 :             :         }
    1444                 :           1 :         val = PQgetvalue(res, 0, 0);
    1445                 :             : 
    1446         [ -  + ]:           1 :         if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
    1447                 :             :         {
    1448                 :           0 :             PQclear(res);
    1449                 :           0 :             libpq_append_conn_error(conn, "\"password_encryption\" value too long");
    1450                 :           0 :             return NULL;
    1451                 :             :         }
    1452                 :           1 :         strcpy(algobuf, val);
    1453                 :           1 :         PQclear(res);
    1454                 :             : 
    1455                 :           1 :         algorithm = algobuf;
    1456                 :             :     }
    1457                 :             : 
    1458                 :             :     /*
    1459                 :             :      * Also accept "on" and "off" as aliases for "md5", because
    1460                 :             :      * password_encryption was a boolean before PostgreSQL 10.  We refuse to
    1461                 :             :      * send the password in plaintext even if it was "off".
    1462                 :             :      */
    1463         [ +  - ]:           1 :     if (strcmp(algorithm, "on") == 0 ||
    1464         [ -  + ]:           1 :         strcmp(algorithm, "off") == 0)
    1465                 :           0 :         algorithm = "md5";
    1466                 :             : 
    1467                 :             :     /*
    1468                 :             :      * Ok, now we know what algorithm to use
    1469                 :             :      */
    1470         [ +  - ]:           1 :     if (strcmp(algorithm, "scram-sha-256") == 0)
    1471                 :             :     {
    1472                 :           1 :         const char *errstr = NULL;
    1473                 :             : 
    1474                 :           1 :         crypt_pwd = pg_fe_scram_build_secret(passwd,
    1475                 :             :                                              conn->scram_sha_256_iterations,
    1476                 :             :                                              &errstr);
    1477         [ -  + ]:           1 :         if (!crypt_pwd)
    1478                 :           0 :             libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
    1479                 :             :     }
    1480         [ #  # ]:           0 :     else if (strcmp(algorithm, "md5") == 0)
    1481                 :             :     {
    1482                 :           0 :         crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
    1483         [ #  # ]:           0 :         if (crypt_pwd)
    1484                 :             :         {
    1485                 :           0 :             const char *errstr = NULL;
    1486                 :             : 
    1487         [ #  # ]:           0 :             if (!pg_md5_encrypt(passwd, (const uint8 *) user, strlen(user), crypt_pwd, &errstr))
    1488                 :             :             {
    1489                 :           0 :                 libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
    1490                 :           0 :                 free(crypt_pwd);
    1491                 :           0 :                 crypt_pwd = NULL;
    1492                 :             :             }
    1493                 :             :         }
    1494                 :             :         else
    1495                 :           0 :             libpq_append_conn_error(conn, "out of memory");
    1496                 :             :     }
    1497                 :             :     else
    1498                 :             :     {
    1499                 :           0 :         libpq_append_conn_error(conn, "unrecognized password encryption algorithm \"%s\"",
    1500                 :             :                                 algorithm);
    1501                 :           0 :         return NULL;
    1502                 :             :     }
    1503                 :             : 
    1504                 :           1 :     return crypt_pwd;
    1505                 :             : }
    1506                 :             : 
    1507                 :             : /*
    1508                 :             :  * PQchangePassword -- exported routine to change a password
    1509                 :             :  *
    1510                 :             :  * This is intended to be used by client applications that wish to
    1511                 :             :  * change the password for a user. The password is not sent in
    1512                 :             :  * cleartext because it is encrypted on the client side. This is
    1513                 :             :  * good because it ensures the cleartext password is never known by
    1514                 :             :  * the server, and therefore won't end up in logs, pg_stat displays,
    1515                 :             :  * etc. The password encryption is performed by PQencryptPasswordConn(),
    1516                 :             :  * which is passed a NULL for the algorithm argument. Hence encryption
    1517                 :             :  * is done according to the server's password_encryption
    1518                 :             :  * setting. We export the function so that clients won't be dependent
    1519                 :             :  * on the implementation specific details with respect to how the
    1520                 :             :  * server changes passwords.
    1521                 :             :  *
    1522                 :             :  * Arguments are a connection object, the SQL name of the target user,
    1523                 :             :  * and the cleartext password.
    1524                 :             :  *
    1525                 :             :  * Return value is the PGresult of the executed ALTER USER statement
    1526                 :             :  * or NULL if we never get there. The caller is responsible to PQclear()
    1527                 :             :  * the returned PGresult.
    1528                 :             :  *
    1529                 :             :  * PQresultStatus() should be called to check the return value for errors,
    1530                 :             :  * and PQerrorMessage() used to get more information about such errors.
    1531                 :             :  */
    1532                 :             : PGresult *
    1533                 :           1 : PQchangePassword(PGconn *conn, const char *user, const char *passwd)
    1534                 :             : {
    1535                 :           1 :     char       *encrypted_password = PQencryptPasswordConn(conn, passwd,
    1536                 :             :                                                            user, NULL);
    1537                 :             : 
    1538         [ -  + ]:           1 :     if (!encrypted_password)
    1539                 :             :     {
    1540                 :             :         /* PQencryptPasswordConn() already registered the error */
    1541                 :           0 :         return NULL;
    1542                 :             :     }
    1543                 :             :     else
    1544                 :             :     {
    1545                 :           1 :         char       *fmtpw = PQescapeLiteral(conn, encrypted_password,
    1546                 :             :                                             strlen(encrypted_password));
    1547                 :             : 
    1548                 :             :         /* no longer needed, so clean up now */
    1549                 :           1 :         PQfreemem(encrypted_password);
    1550                 :             : 
    1551         [ -  + ]:           1 :         if (!fmtpw)
    1552                 :             :         {
    1553                 :             :             /* PQescapeLiteral() already registered the error */
    1554                 :           0 :             return NULL;
    1555                 :             :         }
    1556                 :             :         else
    1557                 :             :         {
    1558                 :           1 :             char       *fmtuser = PQescapeIdentifier(conn, user, strlen(user));
    1559                 :             : 
    1560         [ -  + ]:           1 :             if (!fmtuser)
    1561                 :             :             {
    1562                 :             :                 /* PQescapeIdentifier() already registered the error */
    1563                 :           0 :                 PQfreemem(fmtpw);
    1564                 :           0 :                 return NULL;
    1565                 :             :             }
    1566                 :             :             else
    1567                 :             :             {
    1568                 :             :                 PQExpBufferData buf;
    1569                 :             :                 PGresult   *res;
    1570                 :             : 
    1571                 :           1 :                 initPQExpBuffer(&buf);
    1572                 :           1 :                 printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD %s",
    1573                 :             :                                   fmtuser, fmtpw);
    1574                 :             : 
    1575                 :           1 :                 res = PQexec(conn, buf.data);
    1576                 :             : 
    1577                 :             :                 /* clean up */
    1578                 :           1 :                 termPQExpBuffer(&buf);
    1579                 :           1 :                 PQfreemem(fmtuser);
    1580                 :           1 :                 PQfreemem(fmtpw);
    1581                 :             : 
    1582                 :           1 :                 return res;
    1583                 :             :             }
    1584                 :             :         }
    1585                 :             :     }
    1586                 :             : }
    1587                 :             : 
    1588                 :             : PQauthDataHook_type PQauthDataHook = PQdefaultAuthDataHook;
    1589                 :             : 
    1590                 :             : PQauthDataHook_type
    1591                 :           0 : PQgetAuthDataHook(void)
    1592                 :             : {
    1593                 :           0 :     return PQauthDataHook;
    1594                 :             : }
    1595                 :             : 
    1596                 :             : void
    1597                 :           0 : PQsetAuthDataHook(PQauthDataHook_type hook)
    1598                 :             : {
    1599         [ #  # ]:           0 :     PQauthDataHook = hook ? hook : PQdefaultAuthDataHook;
    1600                 :           0 : }
    1601                 :             : 
    1602                 :             : int
    1603                 :           0 : PQdefaultAuthDataHook(PGauthData type, PGconn *conn, void *data)
    1604                 :             : {
    1605                 :           0 :     return 0;                   /* handle nothing */
    1606                 :             : }
        

Generated by: LCOV version 2.0-1