LCOV - differential code coverage report
Current view: top level - src/interfaces/libpq - fe-auth.c (source / functions) Coverage Total Hit UNC LBC UIC UBC GBC GIC GNC CBC EUB ECB DUB DCB
Current: Differential Code Coverage HEAD vs 15 Lines: 65.8 % 365 240 34 15 64 12 16 137 43 44 75 142 22 39
Current Date: 2023-04-08 15:15:32 Functions: 91.7 % 12 11 1 9 2 1 9 1
Baseline: 15
Baseline Date: 2023-04-08 15:09:40
Legend: Lines: hit not hit

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

Generated by: LCOV version v1.16-55-g56c0a2a