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 17:13:01 Functions: 91.7 % 12 11 1 9 2 1 9 1
Baseline: 15 Line coverage date bins:
Baseline Date: 2023-04-08 15:09:40 [..60] days: 81.8 % 44 36 8 36
Legend: Lines: hit not hit (120,180] days: 10.7 % 28 3 25 3
(240..) days: 68.6 % 293 201 1 15 64 12 16 137 4 44 62 136
Function coverage date bins:
[..60] days: 100.0 % 1 1 1
(240..) days: 47.6 % 21 10 1 9 1 1 9

 Age         Owner                  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
 2187 heikki.linnakangas         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                 :         {
  145 peter                      75 UNC           0 :             libpq_append_conn_error(conn, "out of memory allocating GSSAPI buffer (%d)",
                                 76                 :                                     payloadlen);
 2187 heikki.linnakangas         77 UIC           0 :             return STATUS_ERROR;
 2187 heikki.linnakangas         78 ECB             :         }
 2187 heikki.linnakangas         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.
 2187 heikki.linnakangas         84 EUB             :              */
 2187 heikki.linnakangas         85 UBC           0 :             free(ginbuf.value);
 2187 heikki.linnakangas         86 UIC           0 :             return STATUS_ERROR;
                                 87                 :         }
                                 88                 :     }
                                 89                 :     else
 2132 heikki.linnakangas         90 ECB             :     {
 2132 heikki.linnakangas         91 CBC           6 :         ginbuf.length = 0;
 2132 heikki.linnakangas         92 GIC           6 :         ginbuf.value = NULL;
                                 93                 :     }
 5752 magnus                     94 ECB             : 
 5752 magnus                     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,
 5624 bruce                     102 ECB             :                                     GSS_C_NO_CHANNEL_BINDINGS,
 2118 tgl                       103 GIC          11 :                                     (ginbuf.value == NULL) ? GSS_C_NO_BUFFER : &ginbuf,
                                104                 :                                     NULL,
                                105                 :                                     &goutbuf,
                                106                 :                                     NULL,
                                107                 :                                     NULL);
 5752 magnus                    108 ECB             : 
  297 peter                     109 GNC          11 :     free(ginbuf.value);
                                110                 : 
 2187 heikki.linnakangas        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
 5624 bruce                     116 ECB             :          * packet.
 5752 magnus                    117                 :          */
 5752 magnus                    118 GIC           5 :         if (pqPacketSend(conn, 'p',
 2187 heikki.linnakangas        119 GBC           5 :                          goutbuf.value, goutbuf.length) != STATUS_OK)
 5752 magnus                    120 EUB             :         {
 2187 heikki.linnakangas        121 UIC           0 :             gss_release_buffer(&lmin_s, &goutbuf);
 5752 magnus                    122               0 :             return STATUS_ERROR;
 5752 magnus                    123 ECB             :         }
                                124                 :     }
 2187 heikki.linnakangas        125 CBC          11 :     gss_release_buffer(&lmin_s, &goutbuf);
                                126                 : 
 5752 magnus                    127              11 :     if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
                                128                 :     {
 5752 magnus                    129 GIC           1 :         pg_GSS_error(libpq_gettext("GSSAPI continuation error"),
 5624 bruce                     130 ECB             :                      conn,
                                131                 :                      maj_stat, min_stat);
 5752 magnus                    132 GBC           1 :         gss_release_name(&lmin_s, &conn->gtarg_nam);
 5752 magnus                    133 CBC           1 :         if (conn->gctx)
 5752 magnus                    134 UIC           0 :             gss_delete_sec_context(&lmin_s, &conn->gctx, GSS_C_NO_BUFFER);
 5752 magnus                    135 GIC           1 :         return STATUS_ERROR;
 5752 magnus                    136 ECB             :     }
                                137                 : 
 5752 magnus                    138 CBC          10 :     if (maj_stat == GSS_S_COMPLETE)
                                139                 :     {
   26 michael                   140 GNC           5 :         conn->client_finished_auth = true;
 5752 magnus                    141 CBC           5 :         gss_release_name(&lmin_s, &conn->gtarg_nam);
                                142                 :     }
                                143                 : 
 5752 magnus                    144 GIC          10 :     return STATUS_OK;
 5752 magnus                    145 ECB             : }
                                146                 : 
                                147                 : /*
                                148                 :  * Send initial GSS authentication token
                                149                 :  */
                                150                 : static int
 2187 heikki.linnakangas        151 GIC           6 : pg_GSS_startup(PGconn *conn, int payloadlen)
 5752 magnus                    152 ECB             : {
                                153                 :     int         ret;
 1710 tgl                       154 GIC           6 :     char       *host = conn->connhost[conn->whichhost].host;
 5752 magnus                    155 ECB             : 
 2329 rhaas                     156 GIC           6 :     if (!(host && host[0] != '\0'))
 4780 magnus                    157 ECB             :     {
  145 peter                     158 UNC           0 :         libpq_append_conn_error(conn, "host name must be specified");
 4780 magnus                    159 UBC           0 :         return STATUS_ERROR;
                                160                 :     }
                                161                 : 
 5752 magnus                    162 CBC           6 :     if (conn->gctx)
                                163                 :     {
  145 peter                     164 UNC           0 :         libpq_append_conn_error(conn, "duplicate GSS authentication request");
 5752 magnus                    165 UIC           0 :         return STATUS_ERROR;
                                166                 :     }
 5752 magnus                    167 ECB             : 
 1467 sfrost                    168 CBC           6 :     ret = pg_GSS_load_servicename(conn);
 1467 sfrost                    169 GBC           6 :     if (ret != STATUS_OK)
 1467 sfrost                    170 UIC           0 :         return ret;
                                171                 : 
                                172                 :     /*
                                173                 :      * Initial packet is the same as a continuation packet with no initial
                                174                 :      * context.
 5752 magnus                    175 ECB             :      */
 5752 magnus                    176 GIC           6 :     conn->gctx = GSS_C_NO_CONTEXT;
 5752 magnus                    177 ECB             : 
 2187 heikki.linnakangas        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 */
 6383 tgl                       407 ECB             : 
                                408                 : /*
 2224 heikki.linnakangas        409                 :  * Initialize SASL authentication exchange.
                                410                 :  */
                                411                 : static int
 2187 heikki.linnakangas        412 GIC          35 : pg_SASL_init(PGconn *conn, int payloadlen)
                                413                 : {
                                414              35 :     char       *initialresponse = NULL;
                                415                 :     int         initialresponselen;
                                416                 :     bool        done;
 2187 heikki.linnakangas        417 ECB             :     bool        success;
                                418                 :     const char *selected_mechanism;
                                419                 :     PQExpBufferData mechanism_buf;
 1968 peter_e                   420                 :     char       *password;
                                421                 : 
 2187 heikki.linnakangas        422 CBC          35 :     initPQExpBuffer(&mechanism_buf);
 2187 heikki.linnakangas        423 ECB             : 
 1294 jdavis                    424 GIC          35 :     if (conn->channel_binding[0] == 'r' &&   /* require */
                                425               4 :         !conn->ssl_in_use)
 1294 jdavis                    426 ECB             :     {
  145 peter                     427 GNC           1 :         libpq_append_conn_error(conn, "channel binding required, but SSL not in use");
 1294 jdavis                    428 GBC           1 :         goto error;
                                429                 :     }
                                430                 : 
 2187 heikki.linnakangas        431 GIC          34 :     if (conn->sasl_state)
                                432                 :     {
  145 peter                     433 UNC           0 :         libpq_append_conn_error(conn, "duplicate SASL authentication request");
 2187 heikki.linnakangas        434 UIC           0 :         goto error;
                                435                 :     }
 2187 heikki.linnakangas        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
 1968 peter_e                   441 EUB             :      * supported at the moment, listed by order of decreasing importance.
                                442                 :      */
 2187 heikki.linnakangas        443 GBC          34 :     selected_mechanism = NULL;
                                444                 :     for (;;)
 2224 heikki.linnakangas        445 ECB             :     {
 2187 heikki.linnakangas        446 GBC          75 :         if (pqGets(&mechanism_buf, conn))
                                447                 :         {
  818 tgl                       448 UIC           0 :             appendPQExpBufferStr(&conn->errorMessage,
  818 tgl                       449 ECB             :                                  "fe_sendauth: invalid authentication request from server: invalid list of authentication mechanisms\n");
 2187 heikki.linnakangas        450 LBC           0 :             goto error;
                                451                 :         }
 2187 heikki.linnakangas        452 GIC          75 :         if (PQExpBufferDataBroken(mechanism_buf))
 2187 heikki.linnakangas        453 UIC           0 :             goto oom_error;
                                454                 : 
                                455                 :         /* An empty string indicates end of list */
 2187 heikki.linnakangas        456 GIC          75 :         if (mechanism_buf.data[0] == '\0')
                                457              34 :             break;
                                458                 : 
 2187 heikki.linnakangas        459 ECB             :         /*
                                460                 :          * Select the mechanism to use.  Pick SCRAM-SHA-256-PLUS over anything
 1294 jdavis                    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                 :          */
 1708 heikki.linnakangas        466 GIC          41 :         if (strcmp(mechanism_buf.data, SCRAM_SHA_256_PLUS_NAME) == 0)
                                467                 :         {
                                468               7 :             if (conn->ssl_in_use)
                                469                 :             {
 1286 michael                   470 ECB             :                 /* The server has offered SCRAM-SHA-256-PLUS. */
                                471                 : 
                                472                 : #ifdef HAVE_PGTLS_GET_PEER_CERTIFICATE_HASH
 1501                           473                 :                 /*
                                474                 :                  * The client supports channel binding, which is chosen if
                                475                 :                  * channel_binding is not disabled.
                                476                 :                  */
 1294 jdavis                    477 GIC           7 :                 if (conn->channel_binding[0] != 'd') /* disable */
                                478                 :                 {
                                479               5 :                     selected_mechanism = SCRAM_SHA_256_PLUS_NAME;
  641 michael                   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                 :                 /*
 1708 heikki.linnakangas        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
 1708 heikki.linnakangas        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                 :                  */
  145 peter                     507 UNC           0 :                 libpq_append_conn_error(conn, "server offered SCRAM-SHA-256-PLUS authentication over a non-SSL connection");
 1708 heikki.linnakangas        508 UIC           0 :                 goto error;
                                509                 :             }
 1708 heikki.linnakangas        510 ECB             :         }
 1895 peter_e                   511 GIC          34 :         else if (strcmp(mechanism_buf.data, SCRAM_SHA_256_NAME) == 0 &&
 1968 peter_e                   512 EUB             :                  !selected_mechanism)
  641 michael                   513                 :         {
 1895 peter_e                   514 GIC          29 :             selected_mechanism = SCRAM_SHA_256_NAME;
  641 michael                   515              29 :             conn->sasl = &pg_scram_mech;
  641 michael                   516 ECB             :         }
 2224 heikki.linnakangas        517                 :     }
                                518                 : 
 1288 tgl                       519 GBC          34 :     if (!selected_mechanism)
 1294 jdavis                    520 EUB             :     {
  145 peter                     521 UNC           0 :         libpq_append_conn_error(conn, "none of the server's SASL authentication mechanisms are supported");
 1294 jdavis                    522 UIC           0 :         goto error;
                                523                 :     }
                                524                 : 
 1288 tgl                       525 GIC          34 :     if (conn->channel_binding[0] == 'r' &&   /* require */
                                526               3 :         strcmp(selected_mechanism, SCRAM_SHA_256_PLUS_NAME) != 0)
                                527                 :     {
  145 peter                     528 UNC           0 :         libpq_append_conn_error(conn, "channel binding is required, but server did not offer an authentication method that supports channel binding");
 2187 heikki.linnakangas        529 UIC           0 :         goto error;
                                530                 :     }
 2187 heikki.linnakangas        531 ECB             : 
 1968 peter_e                   532                 :     /*
                                533                 :      * Now that the SASL mechanism has been chosen for the exchange,
                                534                 :      * initialize its state information.
                                535                 :      */
                                536                 : 
 1968 peter_e                   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                 :      */
 1968 peter_e                   542 CBC          34 :     conn->password_needed = true;
 1968 peter_e                   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                 :     {
  818 tgl                       548 UIC           0 :         appendPQExpBufferStr(&conn->errorMessage,
                                549                 :                              PQnoPasswordSupplied);
 1968 peter_e                   550 LBC           0 :         goto error;
                                551                 :     }
                                552                 : 
  641 michael                   553 CBC          34 :     Assert(conn->sasl);
  641 michael                   554 EUB             : 
                                555                 :     /*
                                556                 :      * Initialize the SASL state information with all the information gathered
 1957 rhaas                     557 ECB             :      * during the initial exchange.
                                558                 :      *
                                559                 :      * Note: Only tls-unique is supported for the moment.
                                560                 :      */
  641 michael                   561 GIC          34 :     conn->sasl_state = conn->sasl->init(conn,
 1968 peter_e                   562 ECB             :                                         password,
 1921 peter_e                   563 EUB             :                                         selected_mechanism);
 1968 peter_e                   564 GIC          34 :     if (!conn->sasl_state)
 1968 peter_e                   565 UIC           0 :         goto oom_error;
                                566                 : 
                                567                 :     /* Get the mechanism-specific Initial Client Response, if any */
  641 michael                   568 CBC          34 :     conn->sasl->exchange(conn->sasl_state,
 2187 heikki.linnakangas        569 EUB             :                          NULL, -1,
 2187 heikki.linnakangas        570 ECB             :                          &initialresponse, &initialresponselen,
 1921 peter_e                   571 EUB             :                          &done, &success);
 2187 heikki.linnakangas        572 ECB             : 
 2187 heikki.linnakangas        573 GIC          34 :     if (done && !success)
 2187 heikki.linnakangas        574 LBC           0 :         goto error;
 2187 heikki.linnakangas        575 EUB             : 
 2187 heikki.linnakangas        576 ECB             :     /*
 2187 heikki.linnakangas        577 EUB             :      * Build a SASLInitialResponse message, and send it.
                                578                 :      */
  766 heikki.linnakangas        579 CBC          34 :     if (pqPutMsgStart('p', conn))
 2187 heikki.linnakangas        580 UBC           0 :         goto error;
 2187 heikki.linnakangas        581 CBC          34 :     if (pqPuts(selected_mechanism, conn))
 2187 heikki.linnakangas        582 UBC           0 :         goto error;
 2187 heikki.linnakangas        583 GIC          34 :     if (initialresponse)
 2187 heikki.linnakangas        584 ECB             :     {
 2187 heikki.linnakangas        585 CBC          34 :         if (pqPutInt(initialresponselen, 4, conn))
 2187 heikki.linnakangas        586 UIC           0 :             goto error;
 2187 heikki.linnakangas        587 CBC          34 :         if (pqPutnchar(initialresponse, initialresponselen, conn))
 2187 heikki.linnakangas        588 UIC           0 :             goto error;
 2187 heikki.linnakangas        589 ECB             :     }
 2187 heikki.linnakangas        590 CBC          34 :     if (pqPutMsgEnd(conn))
 2187 heikki.linnakangas        591 LBC           0 :         goto error;
 2187 heikki.linnakangas        592 CBC          34 :     if (pqFlush(conn))
 2187 heikki.linnakangas        593 UIC           0 :         goto error;
 2187 heikki.linnakangas        594 EUB             : 
 2187 heikki.linnakangas        595 GBC          34 :     termPQExpBuffer(&mechanism_buf);
  297 peter                     596 GNC          34 :     free(initialresponse);
 2187 heikki.linnakangas        597 EUB             : 
 2187 heikki.linnakangas        598 GIC          34 :     return STATUS_OK;
                                599                 : 
                                600               1 : error:
                                601               1 :     termPQExpBuffer(&mechanism_buf);
  297 peter                     602 GNC           1 :     free(initialresponse);
 2187 heikki.linnakangas        603 GIC           1 :     return STATUS_ERROR;
                                604                 : 
 2187 heikki.linnakangas        605 LBC           0 : oom_error:
 2187 heikki.linnakangas        606 UIC           0 :     termPQExpBuffer(&mechanism_buf);
  297 peter                     607 UNC           0 :     free(initialresponse);
  145                           608               0 :     libpq_append_conn_error(conn, "out of memory");
 2187 heikki.linnakangas        609 UIC           0 :     return STATUS_ERROR;
                                610                 : }
                                611                 : 
                                612                 : /*
 2224 heikki.linnakangas        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.
 2224 heikki.linnakangas        616 EUB             :  */
                                617                 : static int
 2187 heikki.linnakangas        618 GBC          62 : pg_SASL_continue(PGconn *conn, int payloadlen, bool final)
                                619                 : {
                                620                 :     char       *output;
 2224 heikki.linnakangas        621 ECB             :     int         outputlen;
                                622                 :     bool        done;
 2224 heikki.linnakangas        623 EUB             :     bool        success;
                                624                 :     int         res;
                                625                 :     char       *challenge;
                                626                 : 
 2187 heikki.linnakangas        627 ECB             :     /* Read the SASL challenge from the AuthenticationSASLContinue message. */
 2187 heikki.linnakangas        628 GIC          62 :     challenge = malloc(payloadlen + 1);
 2187 heikki.linnakangas        629 CBC          62 :     if (!challenge)
                                630                 :     {
  145 peter                     631 UNC           0 :         libpq_append_conn_error(conn, "out of memory allocating SASL buffer (%d)",
                                632                 :                                 payloadlen);
 2187 heikki.linnakangas        633 UIC           0 :         return STATUS_ERROR;
 2187 heikki.linnakangas        634 ECB             :     }
                                635                 : 
 2187 heikki.linnakangas        636 GBC          62 :     if (pqGetnchar(challenge, payloadlen, conn))
 2187 heikki.linnakangas        637 EUB             :     {
 2187 heikki.linnakangas        638 UIC           0 :         free(challenge);
 2187 heikki.linnakangas        639 UBC           0 :         return STATUS_ERROR;
 2187 heikki.linnakangas        640 EUB             :     }
                                641                 :     /* For safety and convenience, ensure the buffer is NULL-terminated. */
 2187 heikki.linnakangas        642 GIC          62 :     challenge[payloadlen] = '\0';
                                643                 : 
  641 michael                   644              62 :     conn->sasl->exchange(conn->sasl_state,
                                645                 :                          challenge, payloadlen,
                                646                 :                          &output, &outputlen,
 1921 peter_e                   647 ECB             :                          &done, &success);
 2187 heikki.linnakangas        648 GIC          62 :     free(challenge);            /* don't need the input anymore */
 2187 heikki.linnakangas        649 EUB             : 
 2187 heikki.linnakangas        650 GBC          62 :     if (final && !done)
                                651                 :     {
 2187 heikki.linnakangas        652 UIC           0 :         if (outputlen != 0)
                                653               0 :             free(output);
                                654                 : 
  145 peter                     655 UNC           0 :         libpq_append_conn_error(conn, "AuthenticationSASLFinal received from server, but SASL authentication was not completed");
 2187 heikki.linnakangas        656 LBC           0 :         return STATUS_ERROR;
                                657                 :     }
                                658                 : 
                                659                 :     /*
                                660                 :      * If the exchange is not completed yet, we need to make sure that the
  638 michael                   661 ECB             :      * SASL mechanism has generated a message to send back.
                                662                 :      */
  638 michael                   663 GIC          62 :     if (output == NULL && !done)
  638 michael                   664 ECB             :     {
  145 peter                     665 UNC           0 :         libpq_append_conn_error(conn, "no client response found after SASL exchange success");
  638 michael                   666 UIC           0 :         return STATUS_ERROR;
  638 michael                   667 ECB             :     }
  638 michael                   668 EUB             : 
                                669                 :     /*
  638 michael                   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                 :      */
  638 michael                   673 GIC          62 :     if (output)
 2224 heikki.linnakangas        674 ECB             :     {
                                675                 :         /*
                                676                 :          * Send the SASL response to the server.
 2187                           677                 :          */
 2224 heikki.linnakangas        678 GIC          34 :         res = pqPacketSend(conn, 'p', output, outputlen);
                                679              34 :         free(output);
                                680                 : 
                                681              34 :         if (res != STATUS_OK)
 2224 heikki.linnakangas        682 LBC           0 :             return STATUS_ERROR;
                                683                 :     }
 2224 heikki.linnakangas        684 ECB             : 
 2224 heikki.linnakangas        685 GBC          62 :     if (done && !success)
 2224 heikki.linnakangas        686 UIC           0 :         return STATUS_ERROR;
                                687                 : 
 2224 heikki.linnakangas        688 GIC          62 :     return STATUS_OK;
                                689                 : }
 2224 heikki.linnakangas        690 ECB             : 
 9524 scrappy                   691 EUB             : static int
 9204 scrappy                   692 CBC          44 : pg_password_sendauth(PGconn *conn, const char *password, AuthRequest areq)
                                693                 : {
                                694                 :     int         ret;
 4051 peter_e                   695              44 :     char       *crypt_pwd = NULL;
                                696                 :     const char *pwd_to_send;
                                697                 :     char        md5Salt[4];
 2187 heikki.linnakangas        698 EUB             : 
                                699                 :     /* Read the salt from the AuthenticationMD5Password message. */
 2187 heikki.linnakangas        700 GIC          44 :     if (areq == AUTH_REQ_MD5)
                                701                 :     {
                                702               6 :         if (pqGetnchar(md5Salt, 4, conn))
 2187 heikki.linnakangas        703 UIC           0 :             return STATUS_ERROR;    /* shouldn't happen */
                                704                 :     }
                                705                 : 
                                706                 :     /* Encrypt the password if needed. */
                                707                 : 
 7907 bruce                     708 GIC          44 :     switch (areq)
                                709                 :     {
 7905                           710               6 :         case AUTH_REQ_MD5:
                                711                 :             {
                                712                 :                 char       *crypt_pwd2;
  453 michael                   713               6 :                 const char *errstr = NULL;
 7836 bruce                     714 ECB             : 
                                715                 :                 /* Allocate enough space for two MD5 hashes */
 6492 neilc                     716 CBC           6 :                 crypt_pwd = malloc(2 * (MD5_PASSWD_LEN + 1));
                                717               6 :                 if (!crypt_pwd)
                                718                 :                 {
  145 peter                     719 UNC           0 :                     libpq_append_conn_error(conn, "out of memory");
 7836 bruce                     720 UIC           0 :                     return STATUS_ERROR;
 7836 bruce                     721 ECB             :                 }
 6492 neilc                     722                 : 
 6492 neilc                     723 GIC           6 :                 crypt_pwd2 = crypt_pwd + MD5_PASSWD_LEN + 1;
 6383 tgl                       724               6 :                 if (!pg_md5_encrypt(password, conn->pguser,
  453 michael                   725               6 :                                     strlen(conn->pguser), crypt_pwd2,
                                726                 :                                     &errstr))
                                727                 :                 {
  145 peter                     728 UNC           0 :                     libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
 7836 bruce                     729 UBC           0 :                     free(crypt_pwd);
 7836 bruce                     730 UIC           0 :                     return STATUS_ERROR;
 7836 bruce                     731 ECB             :                 }
 2187 heikki.linnakangas        732 GIC           6 :                 if (!pg_md5_encrypt(crypt_pwd2 + strlen("md5"), md5Salt,
  453 michael                   733 ECB             :                                     4, crypt_pwd, &errstr))
 7836 bruce                     734                 :                 {
  145 peter                     735 UNC           0 :                     libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
 7836 bruce                     736 UIC           0 :                     free(crypt_pwd);
                                737               0 :                     return STATUS_ERROR;
                                738                 :                 }
                                739                 : 
 4051 peter_e                   740 GIC           6 :                 pwd_to_send = crypt_pwd;
 7836 bruce                     741 CBC           6 :                 break;
                                742                 :             }
 7901                           743              38 :         case AUTH_REQ_PASSWORD:
 4051 peter_e                   744 GIC          38 :             pwd_to_send = password;
 7907 bruce                     745 CBC          38 :             break;
 7901 bruce                     746 UIC           0 :         default:
                                747               0 :             return STATUS_ERROR;
                                748                 :     }
  766 heikki.linnakangas        749 GIC          44 :     ret = pqPacketSend(conn, 'p', pwd_to_send, strlen(pwd_to_send) + 1);
  297 peter                     750 GNC          44 :     free(crypt_pwd);
 7907 bruce                     751 GIC          44 :     return ret;
                                752                 : }
                                753                 : 
                                754                 : /*
                                755                 :  * Translate a disallowed AuthRequest code into an error message.
                                756                 :  */
                                757                 : static const char *
   26 michael                   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");
   26 michael                   769 UNC           0 :         case AUTH_REQ_SSPI:
                                770               0 :             return libpq_gettext("server requested SSPI authentication");
   26 michael                   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                 : 
   26 michael                   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
 1294 jdavis                    793 CBC        9077 : check_expected_areq(AuthRequest areq, PGconn *conn)
                                794                 : {
 1294 jdavis                    795 GIC        9077 :     bool        result = true;
   26 michael                   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                 : 
   16                           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                 :         {
   16 michael                   810 UNC           0 :             libpq_append_conn_error(conn, "server did not request an SSL certificate");
                                811               0 :             return false;
                                812                 :         }
   16 michael                   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                 :      */
   26                           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                 : 
   26 michael                   892 UNC           0 :             default:
                                893               0 :                 result = false;
                                894               0 :                 break;
                                895                 :         }
                                896                 :     }
                                897                 : 
   26 michael                   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                 :      */
 1294 jdavis                    915 CBC        9051 :     if (conn->channel_binding[0] == 'r' /* require */ )
                                916                 :     {
 1294 jdavis                    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:
  641 michael                   924               4 :                 if (!conn->sasl || !conn->sasl->channel_bound(conn->sasl_state))
                                925                 :                 {
  145 peter                     926 GNC           1 :                     libpq_append_conn_error(conn, "channel binding required, but server authenticated client without channel binding");
 1294 jdavis                    927 CBC           1 :                     result = false;
 1294 jdavis                    928 ECB             :                 }
 1294 jdavis                    929 GIC           4 :                 break;
                                930               3 :             default:
  145 peter                     931 GNC           3 :                 libpq_append_conn_error(conn, "channel binding required but not supported by server's authentication request");
 1294 jdavis                    932 CBC           3 :                 result = false;
 1294 jdavis                    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
 2187 heikki.linnakangas        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
 2187 heikki.linnakangas        949 EUB             :  * the message.
 9770 scrappy                   950                 :  */
                                951                 : int
 2187 heikki.linnakangas        952 GIC        9077 : pg_fe_sendauth(AuthRequest areq, int payloadlen, PGconn *conn)
                                953                 : {
                                954                 :     int         oldmsglen;
  818 tgl                       955 ECB             : 
 1294 jdavis                    956 GIC        9077 :     if (!check_expected_areq(areq, conn))
 1294 jdavis                    957 CBC          30 :         return STATUS_ERROR;
 1294 jdavis                    958 ECB             : 
 9204 scrappy                   959 GIC        9047 :     switch (areq)
 9345 bruce                     960 ECB             :     {
 8397 bruce                     961 GIC        8894 :         case AUTH_REQ_OK:
 9173 bruce                     962 CBC        8894 :             break;
                                963                 : 
 9173 bruce                     964 UIC           0 :         case AUTH_REQ_KRB4:
  145 peter                     965 UNC           0 :             libpq_append_conn_error(conn, "Kerberos 4 authentication not supported");
 8986 bruce                     966 UIC           0 :             return STATUS_ERROR;
                                967                 : 
 9173                           968               0 :         case AUTH_REQ_KRB5:
  145 peter                     969 UNC           0 :             libpq_append_conn_error(conn, "Kerberos 5 authentication not supported");
 8986 bruce                     970 LBC           0 :             return STATUS_ERROR;
                                971                 : 
 5739 magnus                    972 ECB             : #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
 5752 magnus                    973 GIC           6 :         case AUTH_REQ_GSS:
 4453 magnus                    974 ECB             : #if !defined(ENABLE_SSPI)
                                975                 :             /* no native SSPI, so use GSSAPI library for it */
                                976                 :         case AUTH_REQ_SSPI:
                                977                 : #endif
 5752                           978                 :             {
 5624 bruce                     979                 :                 int         r;
                                980                 : 
 5739 magnus                    981 CBC           6 :                 pglock_thread();
 5624 bruce                     982 ECB             : 
                                983                 :                 /*
 5739 magnus                    984                 :                  * If we have both GSS and SSPI support compiled in, use SSPI
 5624 bruce                     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)
 5739 magnus                    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)
 2187 heikki.linnakangas        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
 5739 magnus                   1001               6 :                 if (r != STATUS_OK)
                               1002                 :                 {
                               1003                 :                     /* Error message already filled in. */
                               1004               1 :                     pgunlock_thread();
                               1005               1 :                     return STATUS_ERROR;
                               1006                 :                 }
 5752 magnus                   1007 CBC           5 :                 pgunlock_thread();
                               1008                 :             }
 5752 magnus                   1009 GIC           5 :             break;
                               1010                 : 
 5752 magnus                   1011 CBC           5 :         case AUTH_REQ_GSS_CONT:
 5752 magnus                   1012 ECB             :             {
                               1013                 :                 int         r;
 5624 bruce                    1014                 : 
 5739 magnus                   1015 GIC           5 :                 pglock_thread();
 5739 magnus                   1016 ECB             : #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
                               1017                 :                 if (conn->usesspi)
                               1018                 :                     r = pg_SSPI_continue(conn, payloadlen);
 5739 magnus                   1019 EUB             :                 else
 2187 heikki.linnakangas       1020                 :                     r = pg_GSS_continue(conn, payloadlen);
 5739 magnus                   1021                 : #elif defined(ENABLE_GSS) && !defined(ENABLE_SSPI)
 2187 heikki.linnakangas       1022 GIC           5 :                 r = pg_GSS_continue(conn, payloadlen);
 5739 magnus                   1023 EUB             : #elif !defined(ENABLE_GSS) && defined(ENABLE_SSPI)
 2187 heikki.linnakangas       1024                 :                 r = pg_SSPI_continue(conn, payloadlen);
 5739 magnus                   1025                 : #endif
 5739 magnus                   1026 GIC           5 :                 if (r != STATUS_OK)
                               1027                 :                 {
 5739 magnus                   1028 ECB             :                     /* Error message already filled in. */
 5739 magnus                   1029 UIC           0 :                     pgunlock_thread();
                               1030               0 :                     return STATUS_ERROR;
                               1031                 :                 }
 5752 magnus                   1032 GIC           5 :                 pgunlock_thread();
                               1033                 :             }
                               1034               5 :             break;
                               1035                 : #else                           /* defined(ENABLE_GSS) || defined(ENABLE_SSPI) */
 4453 magnus                   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                 :              */
 5739                          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
 4382 bruce                    1061                 : 
                               1062                 :             /*
 4453 magnus                   1063                 :              * No SSPI support. However, if we have GSSAPI but not SSPI
                               1064                 :              * support, AUTH_REQ_SSPI will have been handled in the codepath
 1378 michael                  1065                 :              * for AUTH_REQ_GSS above, so don't duplicate the case label in
                               1066                 :              * that case.
                               1067                 :              */
                               1068                 : #if !defined(ENABLE_GSS)
 5739 magnus                   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                 : 
 7905 bruce                    1076 UIC           0 :         case AUTH_REQ_CRYPT:
  145 peter                    1077 UNC           0 :             libpq_append_conn_error(conn, "Crypt authentication not supported");
 5276 magnus                   1078 LBC           0 :             return STATUS_ERROR;
                               1079                 : 
 5276 magnus                   1080 GIC          45 :         case AUTH_REQ_MD5:
 7905 bruce                    1081 EUB             :         case AUTH_REQ_PASSWORD:
 9040 scrappy                  1082                 :             {
                               1083                 :                 char       *password;
 2348 rhaas                    1084 ECB             : 
 2266 tgl                      1085 GIC          45 :                 conn->password_needed = true;
 2266 tgl                      1086 CBC          45 :                 password = conn->connhost[conn->whichhost].password;
 2348 rhaas                    1087 GIC          45 :                 if (password == NULL)
                               1088              40 :                     password = conn->pgpass;
                               1089              45 :                 if (password == NULL || password[0] == '\0')
                               1090                 :                 {
  818 tgl                      1091               1 :                     appendPQExpBufferStr(&conn->errorMessage,
                               1092                 :                                          PQnoPasswordSupplied);
 2348 rhaas                    1093               1 :                     return STATUS_ERROR;
                               1094                 :                 }
                               1095              44 :                 if (pg_password_sendauth(conn, password, areq) != STATUS_OK)
                               1096                 :                 {
  818 tgl                      1097 UIC           0 :                     appendPQExpBufferStr(&conn->errorMessage,
                               1098                 :                                          "fe_sendauth: error sending password authentication\n");
 2348 rhaas                    1099               0 :                     return STATUS_ERROR;
                               1100                 :                 }
                               1101                 : 
                               1102                 :                 /* We expect no further authentication requests. */
   26 michael                  1103 GNC          44 :                 conn->client_finished_auth = true;
 2348 rhaas                    1104 GIC          44 :                 break;
                               1105                 :             }
                               1106                 : 
 2224 heikki.linnakangas       1107              35 :         case AUTH_REQ_SASL:
                               1108                 : 
                               1109                 :             /*
                               1110                 :              * The request contains the name (as assigned by IANA) of the
                               1111                 :              * authentication mechanism.
                               1112                 :              */
 2187                          1113              35 :             if (pg_SASL_init(conn, payloadlen) != STATUS_OK)
                               1114                 :             {
                               1115                 :                 /* pg_SASL_init already set the error message */
 2224                          1116               1 :                 return STATUS_ERROR;
                               1117                 :             }
 2187                          1118              34 :             break;
                               1119                 : 
 2224                          1120              62 :         case AUTH_REQ_SASL_CONT:
                               1121                 :         case AUTH_REQ_SASL_FIN:
                               1122              62 :             if (conn->sasl_state == NULL)
                               1123                 :             {
  818 tgl                      1124 UIC           0 :                 appendPQExpBufferStr(&conn->errorMessage,
                               1125                 :                                      "fe_sendauth: invalid authentication request from server: AUTH_REQ_SASL_CONT without AUTH_REQ_SASL\n");
 2224 heikki.linnakangas       1126               0 :                 return STATUS_ERROR;
                               1127                 :             }
  818 tgl                      1128 GIC          62 :             oldmsglen = conn->errorMessage.len;
 2187 heikki.linnakangas       1129              62 :             if (pg_SASL_continue(conn, payloadlen,
                               1130                 :                                  (areq == AUTH_REQ_SASL_FIN)) != STATUS_OK)
 2224 heikki.linnakangas       1131 EUB             :             {
  818 tgl                      1132                 :                 /* Use this message if pg_SASL_continue didn't supply one */
  818 tgl                      1133 UBC           0 :                 if (conn->errorMessage.len == oldmsglen)
  818 tgl                      1134 UIC           0 :                     appendPQExpBufferStr(&conn->errorMessage,
  818 tgl                      1135 ECB             :                                          "fe_sendauth: error in SASL authentication\n");
 2224 heikki.linnakangas       1136 UIC           0 :                 return STATUS_ERROR;
                               1137                 :             }
 2224 heikki.linnakangas       1138 GIC          62 :             break;
                               1139                 : 
 9173 bruce                    1140 UIC           0 :         default:
  145 peter                    1141 UNC           0 :             libpq_append_conn_error(conn, "authentication method %u not supported", areq);
 8986 bruce                    1142 LBC           0 :             return STATUS_ERROR;
                               1143                 :     }
 9204 scrappy                  1144 ECB             : 
 8986 bruce                    1145 GIC        9044 :     return STATUS_OK;
 9770 scrappy                  1146 EUB             : }
                               1147                 : 
                               1148                 : 
                               1149                 : /*
                               1150                 :  * pg_fe_getusername
                               1151                 :  *
  453 tgl                      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 *
  453 tgl                      1160 GIC        8660 : pg_fe_getusername(uid_t user_id, PQExpBuffer errorMessage)
                               1161                 : {
 3010 tgl                      1162 CBC        8660 :     char       *result = NULL;
 7032 neilc                    1163 GIC        8660 :     const char *name = NULL;
                               1164                 : 
 6669 tgl                      1165 ECB             : #ifdef WIN32
                               1166                 :     /* Microsoft recommends buffer size of UNLEN+1, where UNLEN = 256 */
 3010                          1167                 :     char        username[256 + 1];
                               1168                 :     DWORD       namesize = sizeof(username);
 6669                          1169                 : #else
                               1170                 :     char        pwdbuf[BUFSIZ];
                               1171                 : #endif
                               1172                 : 
 6376 bruce                    1173 EUB             :     /*
                               1174                 :      * Some users are using configure --enable-thread-safety-force, so we
  332 tgl                      1175                 :      * might as well do the locking within our library to protect getpwuid().
                               1176                 :      * In fact, application developers can use getpwuid() in their application
  332 tgl                      1177 ECB             :      * if they use the locking call we provide, or install their own locking
                               1178                 :      * function using PQregisterThreadLock().
                               1179                 :      */
 6955 bruce                    1180 GIC        8660 :     pglock_thread();
                               1181                 : 
 9046 bruce                    1182 EUB             : #ifdef WIN32
 3307                          1183                 :     if (GetUserName(username, &namesize))
                               1184                 :         name = username;
 3010 tgl                      1185                 :     else if (errorMessage)
                               1186                 :         libpq_append_error(errorMessage,
                               1187                 :                            "user name lookup failure: error code %lu",
                               1188                 :                            GetLastError());
 9046 bruce                    1189                 : #else
  453 tgl                      1190 GBC        8660 :     if (pg_get_user_name(user_id, pwdbuf, sizeof(pwdbuf)))
                               1191            8660 :         name = pwdbuf;
 3010 tgl                      1192 UIC           0 :     else if (errorMessage)
  453                          1193               0 :         appendPQExpBuffer(errorMessage, "%s\n", pwdbuf);
 9046 bruce                    1194 ECB             : #endif
                               1195                 : 
 3010 tgl                      1196 GIC        8660 :     if (name)
                               1197                 :     {
                               1198            8660 :         result = strdup(name);
                               1199            8660 :         if (result == NULL && errorMessage)
  145 peter                    1200 UNC           0 :             libpq_append_error(errorMessage, "out of memory");
                               1201                 :     }
                               1202                 : 
 6955 bruce                    1203 GIC        8660 :     pgunlock_thread();
                               1204                 : 
 3010 tgl                      1205            8660 :     return result;
                               1206                 : }
                               1207                 : 
  453 tgl                      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 *
  453 tgl                      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
 2167 heikki.linnakangas       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 *
 2167 heikki.linnakangas       1235 UIC           0 : PQencryptPassword(const char *passwd, const char *user)
                               1236                 : {
                               1237                 :     char       *crypt_pwd;
  453 michael                  1238 LBC           0 :     const char *errstr = NULL;
 2167 heikki.linnakangas       1239 ECB             : 
 2167 heikki.linnakangas       1240 UBC           0 :     crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
                               1241               0 :     if (!crypt_pwd)
 2167 heikki.linnakangas       1242 UIC           0 :         return NULL;
                               1243                 : 
  453 michael                  1244 LBC           0 :     if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
                               1245                 :     {
 2167 heikki.linnakangas       1246               0 :         free(crypt_pwd);
                               1247               0 :         return NULL;
 2167 heikki.linnakangas       1248 EUB             :     }
                               1249                 : 
 2167 heikki.linnakangas       1250 UIC           0 :     return crypt_pwd;
 2167 heikki.linnakangas       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 *
 2167 heikki.linnakangas       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];
 2167 heikki.linnakangas       1283 GBC           1 :     char       *crypt_pwd = NULL;
                               1284                 : 
 2167 heikki.linnakangas       1285 GIC           1 :     if (!conn)
 6316 tgl                      1286 UBC           0 :         return NULL;
                               1287                 : 
  415 tgl                      1288 GBC           1 :     pqClearConnErrorState(conn);
  818 tgl                      1289 EUB             : 
 2167 heikki.linnakangas       1290                 :     /* If no algorithm was given, ask the server. */
 2167 heikki.linnakangas       1291 GIC           1 :     if (algorithm == NULL)
 6316 tgl                      1292 EUB             :     {
                               1293                 :         PGresult   *res;
 2167 heikki.linnakangas       1294                 :         char       *val;
                               1295                 : 
 2167 heikki.linnakangas       1296 GIC           1 :         res = PQexec(conn, "show password_encryption");
                               1297               1 :         if (res == NULL)
 2167 heikki.linnakangas       1298 EUB             :         {
                               1299                 :             /* PQexec() should've set conn->errorMessage already */
 2167 heikki.linnakangas       1300 UIC           0 :             return NULL;
                               1301                 :         }
 2167 heikki.linnakangas       1302 GIC           1 :         if (PQresultStatus(res) != PGRES_TUPLES_OK)
                               1303                 :         {
                               1304                 :             /* PQexec() should've set conn->errorMessage already */
 2167 heikki.linnakangas       1305 UIC           0 :             PQclear(res);
                               1306               0 :             return NULL;
                               1307                 :         }
 2167 heikki.linnakangas       1308 GIC           1 :         if (PQntuples(res) != 1 || PQnfields(res) != 1)
                               1309                 :         {
 2167 heikki.linnakangas       1310 UIC           0 :             PQclear(res);
  145 peter                    1311 UNC           0 :             libpq_append_conn_error(conn, "unexpected shape of result set returned for SHOW");
 2167 heikki.linnakangas       1312 UIC           0 :             return NULL;
                               1313                 :         }
 2167 heikki.linnakangas       1314 GIC           1 :         val = PQgetvalue(res, 0, 0);
                               1315                 : 
                               1316               1 :         if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
                               1317                 :         {
 2167 heikki.linnakangas       1318 UIC           0 :             PQclear(res);
  145 peter                    1319 UNC           0 :             libpq_append_conn_error(conn, "password_encryption value too long");
 2167 heikki.linnakangas       1320 UIC           0 :             return NULL;
                               1321                 :         }
 2167 heikki.linnakangas       1322 GIC           1 :         strcpy(algobuf, val);
                               1323               1 :         PQclear(res);
 2167 heikki.linnakangas       1324 ECB             : 
 2167 heikki.linnakangas       1325 GIC           1 :         algorithm = algobuf;
                               1326                 :     }
                               1327                 : 
                               1328                 :     /*
 2166 heikki.linnakangas       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".
 2166 heikki.linnakangas       1332 EUB             :      */
 2166 heikki.linnakangas       1333 GIC           1 :     if (strcmp(algorithm, "on") == 0 ||
 2162 heikki.linnakangas       1334 CBC           1 :         strcmp(algorithm, "off") == 0)
 2166 heikki.linnakangas       1335 UIC           0 :         algorithm = "md5";
                               1336                 : 
 2166 heikki.linnakangas       1337 ECB             :     /*
                               1338                 :      * Ok, now we know what algorithm to use
                               1339                 :      */
 2167 heikki.linnakangas       1340 GIC           1 :     if (strcmp(algorithm, "scram-sha-256") == 0)
                               1341                 :     {
  451 michael                  1342 CBC           1 :         const char *errstr = NULL;
  451 michael                  1343 ECB             : 
   13 dgustafsson              1344 GNC           1 :         crypt_pwd = pg_fe_scram_build_secret(passwd,
                               1345                 :                                              conn->scram_sha_256_iterations,
                               1346                 :                                              &errstr);
  453 tgl                      1347 GIC           1 :         if (!crypt_pwd)
  145 peter                    1348 UNC           0 :             libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
                               1349                 :     }
 2167 heikki.linnakangas       1350 UIC           0 :     else if (strcmp(algorithm, "md5") == 0)
 2167 heikki.linnakangas       1351 EUB             :     {
 2167 heikki.linnakangas       1352 UBC           0 :         crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
 2167 heikki.linnakangas       1353 UIC           0 :         if (crypt_pwd)
 2167 heikki.linnakangas       1354 ECB             :         {
  453 michael                  1355 UIC           0 :             const char *errstr = NULL;
  453 michael                  1356 EUB             : 
  453 michael                  1357 UBC           0 :             if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
 2167 heikki.linnakangas       1358 EUB             :             {
  145 peter                    1359 UNC           0 :                 libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
 2167 heikki.linnakangas       1360 LBC           0 :                 free(crypt_pwd);
 2167 heikki.linnakangas       1361 UIC           0 :                 crypt_pwd = NULL;
 2167 heikki.linnakangas       1362 EUB             :             }
                               1363                 :         }
  453 tgl                      1364                 :         else
  145 peter                    1365 UNC           0 :             libpq_append_conn_error(conn, "out of memory");
 2167 heikki.linnakangas       1366 ECB             :     }
                               1367                 :     else
                               1368                 :     {
  145 peter                    1369 UNC           0 :         libpq_append_conn_error(conn, "unrecognized password encryption algorithm \"%s\"",
                               1370                 :                                 algorithm);
 6316 tgl                      1371 UIC           0 :         return NULL;
                               1372                 :     }
                               1373                 : 
 6316 tgl                      1374 GIC           1 :     return crypt_pwd;
 6316 tgl                      1375 ECB             : }
        

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