LCOV - differential code coverage report
Current view: top level - src/interfaces/libpq - fe-secure-gssapi.c (source / functions) Coverage Total Hit UBC CBC
Current: Differential Code Coverage 16@8cea358b128 vs 17@8cea358b128 Lines: 65.0 % 240 156 84 156
Current Date: 2024-04-14 14:21:10 Functions: 83.3 % 6 5 1 5
Baseline: 16@8cea358b128 Branches: 47.9 % 140 67 73 67
Baseline Date: 2024-04-14 14:21:09 Line coverage date bins:
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed (120,180] days: 100.0 % 6 6 6
(240..) days: 64.1 % 234 150 84 150
Function coverage date bins:
(240..) days: 83.3 % 6 5 1 5
Branch coverage date bins:
(120,180] days: 50.0 % 6 3 3 3
(240..) days: 47.8 % 134 64 70 64

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * fe-secure-gssapi.c
                                  4                 :                :  *   The front-end (client) encryption support for GSSAPI
                                  5                 :                :  *
                                  6                 :                :  * Portions Copyright (c) 2016-2024, PostgreSQL Global Development Group
                                  7                 :                :  *
                                  8                 :                :  * IDENTIFICATION
                                  9                 :                :  *  src/interfaces/libpq/fe-secure-gssapi.c
                                 10                 :                :  *
                                 11                 :                :  *-------------------------------------------------------------------------
                                 12                 :                :  */
                                 13                 :                : 
                                 14                 :                : #include "postgres_fe.h"
                                 15                 :                : 
                                 16                 :                : #include "fe-gssapi-common.h"
                                 17                 :                : #include "libpq-fe.h"
                                 18                 :                : #include "libpq-int.h"
                                 19                 :                : #include "port/pg_bswap.h"
                                 20                 :                : 
                                 21                 :                : 
                                 22                 :                : /*
                                 23                 :                :  * Require encryption support, as well as mutual authentication and
                                 24                 :                :  * tamperproofing measures.
                                 25                 :                :  */
                                 26                 :                : #define GSS_REQUIRED_FLAGS GSS_C_MUTUAL_FLAG | GSS_C_REPLAY_FLAG | \
                                 27                 :                :     GSS_C_SEQUENCE_FLAG | GSS_C_CONF_FLAG | GSS_C_INTEG_FLAG
                                 28                 :                : 
                                 29                 :                : /*
                                 30                 :                :  * Handle the encryption/decryption of data using GSSAPI.
                                 31                 :                :  *
                                 32                 :                :  * In the encrypted data stream on the wire, we break up the data
                                 33                 :                :  * into packets where each packet starts with a uint32-size length
                                 34                 :                :  * word (in network byte order), then encrypted data of that length
                                 35                 :                :  * immediately following.  Decryption yields the same data stream
                                 36                 :                :  * that would appear when not using encryption.
                                 37                 :                :  *
                                 38                 :                :  * Encrypted data typically ends up being larger than the same data
                                 39                 :                :  * unencrypted, so we use fixed-size buffers for handling the
                                 40                 :                :  * encryption/decryption which are larger than PQComm's buffer will
                                 41                 :                :  * typically be to minimize the times where we have to make multiple
                                 42                 :                :  * packets (and therefore multiple recv/send calls for a single
                                 43                 :                :  * read/write call to us).
                                 44                 :                :  *
                                 45                 :                :  * NOTE: The client and server have to agree on the max packet size,
                                 46                 :                :  * because we have to pass an entire packet to GSSAPI at a time and we
                                 47                 :                :  * don't want the other side to send arbitrarily huge packets as we
                                 48                 :                :  * would have to allocate memory for them to then pass them to GSSAPI.
                                 49                 :                :  *
                                 50                 :                :  * Therefore, these two #define's are effectively part of the protocol
                                 51                 :                :  * spec and can't ever be changed.
                                 52                 :                :  */
                                 53                 :                : #define PQ_GSS_SEND_BUFFER_SIZE 16384
                                 54                 :                : #define PQ_GSS_RECV_BUFFER_SIZE 16384
                                 55                 :                : 
                                 56                 :                : /*
                                 57                 :                :  * We need these state variables per-connection.  To allow the functions
                                 58                 :                :  * in this file to look mostly like those in be-secure-gssapi.c, set up
                                 59                 :                :  * these macros.
                                 60                 :                :  */
                                 61                 :                : #define PqGSSSendBuffer (conn->gss_SendBuffer)
                                 62                 :                : #define PqGSSSendLength (conn->gss_SendLength)
                                 63                 :                : #define PqGSSSendNext (conn->gss_SendNext)
                                 64                 :                : #define PqGSSSendConsumed (conn->gss_SendConsumed)
                                 65                 :                : #define PqGSSRecvBuffer (conn->gss_RecvBuffer)
                                 66                 :                : #define PqGSSRecvLength (conn->gss_RecvLength)
                                 67                 :                : #define PqGSSResultBuffer (conn->gss_ResultBuffer)
                                 68                 :                : #define PqGSSResultLength (conn->gss_ResultLength)
                                 69                 :                : #define PqGSSResultNext (conn->gss_ResultNext)
                                 70                 :                : #define PqGSSMaxPktSize (conn->gss_MaxPktSize)
                                 71                 :                : 
                                 72                 :                : 
                                 73                 :                : /*
                                 74                 :                :  * Attempt to write len bytes of data from ptr to a GSSAPI-encrypted connection.
                                 75                 :                :  *
                                 76                 :                :  * The connection must be already set up for GSSAPI encryption (i.e., GSSAPI
                                 77                 :                :  * transport negotiation is complete).
                                 78                 :                :  *
                                 79                 :                :  * On success, returns the number of data bytes consumed (possibly less than
                                 80                 :                :  * len).  On failure, returns -1 with errno set appropriately.  If the errno
                                 81                 :                :  * indicates a non-retryable error, a message is added to conn->errorMessage.
                                 82                 :                :  * For retryable errors, caller should call again (passing the same or more
                                 83                 :                :  * data) once the socket is ready.
                                 84                 :                :  */
                                 85                 :                : ssize_t
 1838 sfrost@snowman.net         86                 :CBC         619 : pg_GSS_write(PGconn *conn, const void *ptr, size_t len)
                                 87                 :                : {
                                 88                 :                :     OM_uint32   major,
                                 89                 :                :                 minor;
                                 90                 :                :     gss_buffer_desc input,
 1555 tgl@sss.pgh.pa.us          91                 :            619 :                 output = GSS_C_EMPTY_BUFFER;
 1838 sfrost@snowman.net         92                 :            619 :     ssize_t     ret = -1;
                                 93                 :                :     size_t      bytes_to_encrypt;
                                 94                 :                :     size_t      bytes_encrypted;
 1555 tgl@sss.pgh.pa.us          95                 :            619 :     gss_ctx_id_t gctx = conn->gctx;
                                 96                 :                : 
                                 97                 :                :     /*
                                 98                 :                :      * When we get a retryable failure, we must not tell the caller we have
                                 99                 :                :      * successfully transmitted everything, else it won't retry.  For
                                100                 :                :      * simplicity, we claim we haven't transmitted anything until we have
                                101                 :                :      * successfully transmitted all "len" bytes.  Between calls, the amount of
                                102                 :                :      * the current input data that's already been encrypted and placed into
                                103                 :                :      * PqGSSSendBuffer (and perhaps transmitted) is remembered in
                                104                 :                :      * PqGSSSendConsumed.  On a retry, the caller *must* be sending that data
                                105                 :                :      * again, so if it offers a len less than that, something is wrong.
                                106                 :                :      *
                                107                 :                :      * Note: it may seem attractive to report partial write completion once
                                108                 :                :      * we've successfully sent any encrypted packets.  However, that can cause
                                109                 :                :      * problems for callers; notably, pqPutMsgEnd's heuristic to send only
                                110                 :                :      * full 8K blocks interacts badly with such a hack.  We won't save much,
                                111                 :                :      * typically, by letting callers discard data early, so don't risk it.
                                112                 :                :      */
                                113         [ -  + ]:            619 :     if (len < PqGSSSendConsumed)
                                114                 :                :     {
 1189 tgl@sss.pgh.pa.us         115                 :UBC           0 :         appendPQExpBufferStr(&conn->errorMessage,
                                116                 :                :                              "GSSAPI caller failed to retransmit all data needing to be retried\n");
 1555                           117                 :              0 :         errno = EINVAL;
                                118                 :              0 :         return -1;
                                119                 :                :     }
                                120                 :                : 
                                121                 :                :     /* Discount whatever source data we already encrypted. */
 1555 tgl@sss.pgh.pa.us         122                 :CBC         619 :     bytes_to_encrypt = len - PqGSSSendConsumed;
                                123                 :            619 :     bytes_encrypted = PqGSSSendConsumed;
                                124                 :                : 
                                125                 :                :     /*
                                126                 :                :      * Loop through encrypting data and sending it out until it's all done or
                                127                 :                :      * pqsecure_raw_write() complains (which would likely mean that the socket
                                128                 :                :      * is non-blocking and the requested send() would block, or there was some
                                129                 :                :      * kind of actual error).
                                130                 :                :      */
                                131   [ +  +  +  - ]:           1238 :     while (bytes_to_encrypt || PqGSSSendLength)
                                132                 :                :     {
 1669 peter@eisentraut.org      133                 :           1238 :         int         conf_state = 0;
                                134                 :                :         uint32      netlen;
                                135                 :                : 
                                136                 :                :         /*
                                137                 :                :          * Check if we have data in the encrypted output buffer that needs to
                                138                 :                :          * be sent (possibly left over from a previous call), and if so, try
                                139                 :                :          * to send it.  If we aren't able to, return that fact back up to the
                                140                 :                :          * caller.
                                141                 :                :          */
 1555 tgl@sss.pgh.pa.us         142         [ +  + ]:           1238 :         if (PqGSSSendLength)
                                143                 :                :         {
                                144                 :                :             ssize_t     retval;
                                145                 :            619 :             ssize_t     amount = PqGSSSendLength - PqGSSSendNext;
                                146                 :                : 
  555 drowley@postgresql.o      147                 :            619 :             retval = pqsecure_raw_write(conn, PqGSSSendBuffer + PqGSSSendNext, amount);
                                148         [ -  + ]:            619 :             if (retval <= 0)
  555 drowley@postgresql.o      149                 :UBC           0 :                 return retval;
                                150                 :                : 
                                151                 :                :             /*
                                152                 :                :              * Check if this was a partial write, and if so, move forward that
                                153                 :                :              * far in our buffer and try again.
                                154                 :                :              */
  143 tgl@sss.pgh.pa.us         155         [ -  + ]:CBC         619 :             if (retval < amount)
                                156                 :                :             {
  555 drowley@postgresql.o      157                 :UBC           0 :                 PqGSSSendNext += retval;
 1838 sfrost@snowman.net        158                 :              0 :                 continue;
                                159                 :                :             }
                                160                 :                : 
                                161                 :                :             /* We've successfully sent whatever data was in the buffer. */
  143 tgl@sss.pgh.pa.us         162                 :CBC         619 :             PqGSSSendLength = PqGSSSendNext = 0;
                                163                 :                :         }
                                164                 :                : 
                                165                 :                :         /*
                                166                 :                :          * Check if there are any bytes left to encrypt.  If not, we're done.
                                167                 :                :          */
 1838 sfrost@snowman.net        168         [ +  + ]:           1238 :         if (!bytes_to_encrypt)
 1555 tgl@sss.pgh.pa.us         169                 :            619 :             break;
                                170                 :                : 
                                171                 :                :         /*
                                172                 :                :          * Check how much we are being asked to send, if it's too much, then
                                173                 :                :          * we will have to loop and possibly be called multiple times to get
                                174                 :                :          * through all the data.
                                175                 :                :          */
                                176         [ -  + ]:            619 :         if (bytes_to_encrypt > PqGSSMaxPktSize)
 1555 tgl@sss.pgh.pa.us         177                 :UBC           0 :             input.length = PqGSSMaxPktSize;
                                178                 :                :         else
 1838 sfrost@snowman.net        179                 :CBC         619 :             input.length = bytes_to_encrypt;
                                180                 :                : 
                                181                 :            619 :         input.value = (char *) ptr + bytes_encrypted;
                                182                 :                : 
                                183                 :            619 :         output.value = NULL;
                                184                 :            619 :         output.length = 0;
                                185                 :                : 
                                186                 :                :         /*
                                187                 :                :          * Create the next encrypted packet.  Any failure here is considered a
                                188                 :                :          * hard failure, so we return -1 even if some data has been sent.
                                189                 :                :          */
 1555 tgl@sss.pgh.pa.us         190                 :            619 :         major = gss_wrap(&minor, gctx, 1, GSS_C_QOP_DEFAULT,
                                191                 :                :                          &input, &conf_state, &output);
 1838 sfrost@snowman.net        192         [ -  + ]:            619 :         if (major != GSS_S_COMPLETE)
                                193                 :                :         {
 1838 sfrost@snowman.net        194                 :UBC           0 :             pg_GSS_error(libpq_gettext("GSSAPI wrap error"), conn, major, minor);
 1555 tgl@sss.pgh.pa.us         195                 :              0 :             errno = EIO;        /* for lack of a better idea */
 1838 sfrost@snowman.net        196                 :              0 :             goto cleanup;
                                197                 :                :         }
                                198                 :                : 
 1555 tgl@sss.pgh.pa.us         199         [ -  + ]:CBC         619 :         if (conf_state == 0)
                                200                 :                :         {
  516 peter@eisentraut.org      201                 :UBC           0 :             libpq_append_conn_error(conn, "outgoing GSSAPI message would not use confidentiality");
 1555 tgl@sss.pgh.pa.us         202                 :              0 :             errno = EIO;        /* for lack of a better idea */
 1838 sfrost@snowman.net        203                 :              0 :             goto cleanup;
                                204                 :                :         }
                                205                 :                : 
 1838 sfrost@snowman.net        206         [ -  + ]:CBC         619 :         if (output.length > PQ_GSS_SEND_BUFFER_SIZE - sizeof(uint32))
                                207                 :                :         {
  516 peter@eisentraut.org      208                 :UBC           0 :             libpq_append_conn_error(conn, "client tried to send oversize GSSAPI packet (%zu > %zu)",
  331 tgl@sss.pgh.pa.us         209                 :              0 :                                     (size_t) output.length,
                                210                 :                :                                     PQ_GSS_SEND_BUFFER_SIZE - sizeof(uint32));
 1555                           211                 :              0 :             errno = EIO;        /* for lack of a better idea */
 1838 sfrost@snowman.net        212                 :              0 :             goto cleanup;
                                213                 :                :         }
                                214                 :                : 
 1838 sfrost@snowman.net        215                 :CBC         619 :         bytes_encrypted += input.length;
                                216                 :            619 :         bytes_to_encrypt -= input.length;
 1555 tgl@sss.pgh.pa.us         217                 :            619 :         PqGSSSendConsumed += input.length;
                                218                 :                : 
                                219                 :                :         /* 4 network-order bytes of length, then payload */
 1277 michael@paquier.xyz       220                 :            619 :         netlen = pg_hton32(output.length);
 1555 tgl@sss.pgh.pa.us         221                 :            619 :         memcpy(PqGSSSendBuffer + PqGSSSendLength, &netlen, sizeof(uint32));
                                222                 :            619 :         PqGSSSendLength += sizeof(uint32);
                                223                 :                : 
                                224                 :            619 :         memcpy(PqGSSSendBuffer + PqGSSSendLength, output.value, output.length);
                                225                 :            619 :         PqGSSSendLength += output.length;
                                226                 :                : 
                                227                 :                :         /* Release buffer storage allocated by GSSAPI */
 1440                           228                 :            619 :         gss_release_buffer(&minor, &output);
                                229                 :                :     }
                                230                 :                : 
                                231                 :                :     /* If we get here, our counters should all match up. */
  143                           232         [ -  + ]:            619 :     Assert(len == PqGSSSendConsumed);
                                233         [ -  + ]:            619 :     Assert(len == bytes_encrypted);
                                234                 :                : 
                                235                 :                :     /* We're reporting all the data as sent, so reset PqGSSSendConsumed. */
                                236                 :            619 :     PqGSSSendConsumed = 0;
                                237                 :                : 
                                238                 :            619 :     ret = bytes_encrypted;
                                239                 :                : 
 1838 sfrost@snowman.net        240                 :            619 : cleanup:
                                241                 :                :     /* Release GSSAPI buffer storage, if we didn't already */
                                242         [ -  + ]:            619 :     if (output.value != NULL)
 1838 sfrost@snowman.net        243                 :UBC           0 :         gss_release_buffer(&minor, &output);
 1838 sfrost@snowman.net        244                 :CBC         619 :     return ret;
                                245                 :                : }
                                246                 :                : 
                                247                 :                : /*
                                248                 :                :  * Read up to len bytes of data into ptr from a GSSAPI-encrypted connection.
                                249                 :                :  *
                                250                 :                :  * The connection must be already set up for GSSAPI encryption (i.e., GSSAPI
                                251                 :                :  * transport negotiation is complete).
                                252                 :                :  *
                                253                 :                :  * Returns the number of data bytes read, or on failure, returns -1
                                254                 :                :  * with errno set appropriately.  If the errno indicates a non-retryable
                                255                 :                :  * error, a message is added to conn->errorMessage.  For retryable errors,
                                256                 :                :  * caller should call again once the socket is ready.
                                257                 :                :  */
                                258                 :                : ssize_t
                                259                 :            750 : pg_GSS_read(PGconn *conn, void *ptr, size_t len)
                                260                 :                : {
                                261                 :                :     OM_uint32   major,
                                262                 :                :                 minor;
                                263                 :            750 :     gss_buffer_desc input = GSS_C_EMPTY_BUFFER,
                                264                 :            750 :                 output = GSS_C_EMPTY_BUFFER;
                                265                 :                :     ssize_t     ret;
                                266                 :            750 :     size_t      bytes_returned = 0;
 1555 tgl@sss.pgh.pa.us         267                 :            750 :     gss_ctx_id_t gctx = conn->gctx;
                                268                 :                : 
                                269                 :                :     /*
                                270                 :                :      * The plan here is to read one incoming encrypted packet into
                                271                 :                :      * PqGSSRecvBuffer, decrypt it into PqGSSResultBuffer, and then dole out
                                272                 :                :      * data from there to the caller.  When we exhaust the current input
                                273                 :                :      * packet, read another.
                                274                 :                :      */
                                275         [ +  - ]:           1346 :     while (bytes_returned < len)
                                276                 :                :     {
 1669 peter@eisentraut.org      277                 :           1346 :         int         conf_state = 0;
                                278                 :                : 
                                279                 :                :         /* Check if we have data in our buffer that we can return immediately */
 1555 tgl@sss.pgh.pa.us         280         [ +  + ]:           1346 :         if (PqGSSResultNext < PqGSSResultLength)
                                281                 :                :         {
                                282                 :            596 :             size_t      bytes_in_buffer = PqGSSResultLength - PqGSSResultNext;
                                283                 :            596 :             size_t      bytes_to_copy = Min(bytes_in_buffer, len - bytes_returned);
                                284                 :                : 
                                285                 :                :             /*
                                286                 :                :              * Copy the data from our result buffer into the caller's buffer,
                                287                 :                :              * at the point where we last left off filling their buffer.
                                288                 :                :              */
                                289                 :            596 :             memcpy((char *) ptr + bytes_returned, PqGSSResultBuffer + PqGSSResultNext, bytes_to_copy);
                                290                 :            596 :             PqGSSResultNext += bytes_to_copy;
 1838 sfrost@snowman.net        291                 :            596 :             bytes_returned += bytes_to_copy;
                                292                 :                : 
                                293                 :                :             /*
                                294                 :                :              * At this point, we've either filled the caller's buffer or
                                295                 :                :              * emptied our result buffer.  Either way, return to caller.  In
                                296                 :                :              * the second case, we could try to read another encrypted packet,
                                297                 :                :              * but the odds are good that there isn't one available.  (If this
                                298                 :                :              * isn't true, we chose too small a max packet size.)  In any
                                299                 :                :              * case, there's no harm letting the caller process the data we've
                                300                 :                :              * already returned.
                                301                 :                :              */
 1555 tgl@sss.pgh.pa.us         302                 :            596 :             break;
                                303                 :                :         }
                                304                 :                : 
                                305                 :                :         /* Result buffer is empty, so reset buffer pointers */
                                306                 :            750 :         PqGSSResultLength = PqGSSResultNext = 0;
                                307                 :                : 
                                308                 :                :         /*
                                309                 :                :          * Because we chose above to return immediately as soon as we emit
                                310                 :                :          * some data, bytes_returned must be zero at this point.  Therefore
                                311                 :                :          * the failure exits below can just return -1 without worrying about
                                312                 :                :          * whether we already emitted some data.
                                313                 :                :          */
                                314         [ -  + ]:            750 :         Assert(bytes_returned == 0);
                                315                 :                : 
                                316                 :                :         /*
                                317                 :                :          * At this point, our result buffer is empty with more bytes being
                                318                 :                :          * requested to be read.  We are now ready to load the next packet and
                                319                 :                :          * decrypt it (entirely) into our result buffer.
                                320                 :                :          */
                                321                 :                : 
                                322                 :                :         /* Collect the length if we haven't already */
 1838 sfrost@snowman.net        323         [ +  - ]:            750 :         if (PqGSSRecvLength < sizeof(uint32))
                                324                 :                :         {
                                325                 :            750 :             ret = pqsecure_raw_read(conn, PqGSSRecvBuffer + PqGSSRecvLength,
                                326                 :            750 :                                     sizeof(uint32) - PqGSSRecvLength);
                                327                 :                : 
                                328                 :                :             /* If ret <= 0, pqsecure_raw_read already set the correct errno */
 1555 tgl@sss.pgh.pa.us         329         [ +  + ]:            750 :             if (ret <= 0)
                                330                 :            154 :                 return ret;
                                331                 :                : 
 1838 sfrost@snowman.net        332                 :            596 :             PqGSSRecvLength += ret;
                                333                 :                : 
                                334                 :                :             /* If we still haven't got the length, return to the caller */
                                335         [ -  + ]:            596 :             if (PqGSSRecvLength < sizeof(uint32))
                                336                 :                :             {
 1555 tgl@sss.pgh.pa.us         337                 :UBC           0 :                 errno = EWOULDBLOCK;
                                338                 :              0 :                 return -1;
                                339                 :                :             }
                                340                 :                :         }
                                341                 :                : 
                                342                 :                :         /* Decode the packet length and check for overlength packet */
 1277 michael@paquier.xyz       343                 :CBC         596 :         input.length = pg_ntoh32(*(uint32 *) PqGSSRecvBuffer);
                                344                 :                : 
 1838 sfrost@snowman.net        345         [ -  + ]:            596 :         if (input.length > PQ_GSS_RECV_BUFFER_SIZE - sizeof(uint32))
                                346                 :                :         {
  516 peter@eisentraut.org      347                 :UBC           0 :             libpq_append_conn_error(conn, "oversize GSSAPI packet sent by the server (%zu > %zu)",
  331 tgl@sss.pgh.pa.us         348                 :              0 :                                     (size_t) input.length,
                                349                 :                :                                     PQ_GSS_RECV_BUFFER_SIZE - sizeof(uint32));
 1555                           350                 :              0 :             errno = EIO;        /* for lack of a better idea */
                                351                 :              0 :             return -1;
                                352                 :                :         }
                                353                 :                : 
                                354                 :                :         /*
                                355                 :                :          * Read as much of the packet as we are able to on this call into
                                356                 :                :          * wherever we left off from the last time we were called.
                                357                 :                :          */
 1838 sfrost@snowman.net        358                 :CBC         596 :         ret = pqsecure_raw_read(conn, PqGSSRecvBuffer + PqGSSRecvLength,
                                359                 :            596 :                                 input.length - (PqGSSRecvLength - sizeof(uint32)));
                                360                 :                :         /* If ret <= 0, pqsecure_raw_read already set the correct errno */
 1555 tgl@sss.pgh.pa.us         361         [ -  + ]:            596 :         if (ret <= 0)
 1555 tgl@sss.pgh.pa.us         362                 :UBC           0 :             return ret;
                                363                 :                : 
 1838 sfrost@snowman.net        364                 :CBC         596 :         PqGSSRecvLength += ret;
                                365                 :                : 
                                366                 :                :         /* If we don't yet have the whole packet, return to the caller */
                                367         [ -  + ]:            596 :         if (PqGSSRecvLength - sizeof(uint32) < input.length)
                                368                 :                :         {
 1555 tgl@sss.pgh.pa.us         369                 :UBC           0 :             errno = EWOULDBLOCK;
                                370                 :              0 :             return -1;
                                371                 :                :         }
                                372                 :                : 
                                373                 :                :         /*
                                374                 :                :          * We now have the full packet and we can perform the decryption and
                                375                 :                :          * refill our result buffer, then loop back up to pass data back to
                                376                 :                :          * the caller.  Note that error exits below here must take care of
                                377                 :                :          * releasing the gss output buffer.
                                378                 :                :          */
 1838 sfrost@snowman.net        379                 :CBC         596 :         output.value = NULL;
                                380                 :            596 :         output.length = 0;
                                381                 :            596 :         input.value = PqGSSRecvBuffer + sizeof(uint32);
                                382                 :                : 
 1555 tgl@sss.pgh.pa.us         383                 :            596 :         major = gss_unwrap(&minor, gctx, &input, &output, &conf_state, NULL);
 1838 sfrost@snowman.net        384         [ -  + ]:            596 :         if (major != GSS_S_COMPLETE)
                                385                 :                :         {
 1838 sfrost@snowman.net        386                 :UBC           0 :             pg_GSS_error(libpq_gettext("GSSAPI unwrap error"), conn,
                                387                 :                :                          major, minor);
                                388                 :              0 :             ret = -1;
 1555 tgl@sss.pgh.pa.us         389                 :              0 :             errno = EIO;        /* for lack of a better idea */
 1838 sfrost@snowman.net        390                 :              0 :             goto cleanup;
                                391                 :                :         }
                                392                 :                : 
 1555 tgl@sss.pgh.pa.us         393         [ -  + ]:CBC         596 :         if (conf_state == 0)
                                394                 :                :         {
  516 peter@eisentraut.org      395                 :UBC           0 :             libpq_append_conn_error(conn, "incoming GSSAPI message did not use confidentiality");
 1838 sfrost@snowman.net        396                 :              0 :             ret = -1;
 1555 tgl@sss.pgh.pa.us         397                 :              0 :             errno = EIO;        /* for lack of a better idea */
 1838 sfrost@snowman.net        398                 :              0 :             goto cleanup;
                                399                 :                :         }
                                400                 :                : 
 1838 sfrost@snowman.net        401                 :CBC         596 :         memcpy(PqGSSResultBuffer, output.value, output.length);
                                402                 :            596 :         PqGSSResultLength = output.length;
                                403                 :                : 
                                404                 :                :         /* Our receive buffer is now empty, reset it */
 1555 tgl@sss.pgh.pa.us         405                 :            596 :         PqGSSRecvLength = 0;
                                406                 :                : 
                                407                 :                :         /* Release buffer storage allocated by GSSAPI */
 1838 sfrost@snowman.net        408                 :            596 :         gss_release_buffer(&minor, &output);
                                409                 :                :     }
                                410                 :                : 
                                411                 :            596 :     ret = bytes_returned;
                                412                 :                : 
                                413                 :            596 : cleanup:
                                414                 :                :     /* Release GSSAPI buffer storage, if we didn't already */
                                415         [ -  + ]:            596 :     if (output.value != NULL)
 1838 sfrost@snowman.net        416                 :UBC           0 :         gss_release_buffer(&minor, &output);
 1838 sfrost@snowman.net        417                 :CBC         596 :     return ret;
                                418                 :                : }
                                419                 :                : 
                                420                 :                : /*
                                421                 :                :  * Simple wrapper for reading from pqsecure_raw_read.
                                422                 :                :  *
                                423                 :                :  * This takes the same arguments as pqsecure_raw_read, plus an output parameter
                                424                 :                :  * to return the number of bytes read.  This handles if blocking would occur and
                                425                 :                :  * if we detect EOF on the connection.
                                426                 :                :  */
                                427                 :                : static PostgresPollingStatusType
                                428                 :            698 : gss_read(PGconn *conn, void *recv_buffer, size_t length, ssize_t *ret)
                                429                 :                : {
                                430                 :            698 :     *ret = pqsecure_raw_read(conn, recv_buffer, length);
 1555 tgl@sss.pgh.pa.us         431         [ +  + ]:            698 :     if (*ret < 0)
                                432                 :                :     {
                                433   [ -  +  -  -  :            232 :         if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
                                              -  - ]
                                434                 :            232 :             return PGRES_POLLING_READING;
                                435                 :                :         else
 1555 tgl@sss.pgh.pa.us         436                 :UBC           0 :             return PGRES_POLLING_FAILED;
                                437                 :                :     }
                                438                 :                : 
                                439                 :                :     /* Check for EOF */
 1838 sfrost@snowman.net        440         [ -  + ]:CBC         466 :     if (*ret == 0)
                                441                 :                :     {
 1838 sfrost@snowman.net        442                 :UBC           0 :         int         result = pqReadReady(conn);
                                443                 :                : 
                                444         [ #  # ]:              0 :         if (result < 0)
                                445                 :              0 :             return PGRES_POLLING_FAILED;
                                446                 :                : 
                                447         [ #  # ]:              0 :         if (!result)
                                448                 :              0 :             return PGRES_POLLING_READING;
                                449                 :                : 
                                450                 :              0 :         *ret = pqsecure_raw_read(conn, recv_buffer, length);
 1555 tgl@sss.pgh.pa.us         451         [ #  # ]:              0 :         if (*ret < 0)
                                452                 :                :         {
                                453   [ #  #  #  #  :              0 :             if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
                                              #  # ]
                                454                 :              0 :                 return PGRES_POLLING_READING;
                                455                 :                :             else
                                456                 :              0 :                 return PGRES_POLLING_FAILED;
                                457                 :                :         }
 1838 sfrost@snowman.net        458         [ #  # ]:              0 :         if (*ret == 0)
                                459                 :              0 :             return PGRES_POLLING_FAILED;
                                460                 :                :     }
                                461                 :                : 
 1838 sfrost@snowman.net        462                 :CBC         466 :     return PGRES_POLLING_OK;
                                463                 :                : }
                                464                 :                : 
                                465                 :                : /*
                                466                 :                :  * Negotiate GSSAPI transport for a connection.  When complete, returns
                                467                 :                :  * PGRES_POLLING_OK.  Will return PGRES_POLLING_READING or
                                468                 :                :  * PGRES_POLLING_WRITING as appropriate whenever it would block, and
                                469                 :                :  * PGRES_POLLING_FAILED if transport could not be negotiated.
                                470                 :                :  */
                                471                 :                : PostgresPollingStatusType
                                472                 :            698 : pqsecure_open_gss(PGconn *conn)
                                473                 :                : {
                                474                 :                :     ssize_t     ret;
                                475                 :                :     OM_uint32   major,
                                476                 :                :                 minor,
  367                           477                 :            698 :                 gss_flags = GSS_REQUIRED_FLAGS;
                                478                 :                :     uint32      netlen;
                                479                 :                :     PostgresPollingStatusType result;
 1838                           480                 :            698 :     gss_buffer_desc input = GSS_C_EMPTY_BUFFER,
                                481                 :            698 :                 output = GSS_C_EMPTY_BUFFER;
                                482                 :                : 
                                483                 :                :     /*
                                484                 :                :      * If first time through for this connection, allocate buffers and
                                485                 :                :      * initialize state variables.  By malloc'ing the buffers separately, we
                                486                 :                :      * ensure that they are sufficiently aligned for the length-word accesses
                                487                 :                :      * that we do in some places in this file.
                                488                 :                :      */
 1555 tgl@sss.pgh.pa.us         489         [ +  + ]:            698 :     if (PqGSSSendBuffer == NULL)
                                490                 :                :     {
                                491                 :            233 :         PqGSSSendBuffer = malloc(PQ_GSS_SEND_BUFFER_SIZE);
                                492                 :            233 :         PqGSSRecvBuffer = malloc(PQ_GSS_RECV_BUFFER_SIZE);
                                493                 :            233 :         PqGSSResultBuffer = malloc(PQ_GSS_RECV_BUFFER_SIZE);
                                494   [ +  -  +  -  :            233 :         if (!PqGSSSendBuffer || !PqGSSRecvBuffer || !PqGSSResultBuffer)
                                              -  + ]
                                495                 :                :         {
  516 peter@eisentraut.org      496                 :UBC           0 :             libpq_append_conn_error(conn, "out of memory");
 1555 tgl@sss.pgh.pa.us         497                 :              0 :             return PGRES_POLLING_FAILED;
                                498                 :                :         }
 1555 tgl@sss.pgh.pa.us         499                 :CBC         233 :         PqGSSSendLength = PqGSSSendNext = PqGSSSendConsumed = 0;
                                500                 :            233 :         PqGSSRecvLength = PqGSSResultLength = PqGSSResultNext = 0;
                                501                 :                :     }
                                502                 :                : 
                                503                 :                :     /*
                                504                 :                :      * Check if we have anything to send from a prior call and if so, send it.
                                505                 :                :      */
                                506         [ +  + ]:            698 :     if (PqGSSSendLength)
                                507                 :                :     {
                                508                 :            233 :         ssize_t     amount = PqGSSSendLength - PqGSSSendNext;
                                509                 :                : 
                                510                 :            233 :         ret = pqsecure_raw_write(conn, PqGSSSendBuffer + PqGSSSendNext, amount);
                                511         [ -  + ]:            233 :         if (ret < 0)
                                512                 :                :         {
 1555 tgl@sss.pgh.pa.us         513   [ #  #  #  #  :UBC           0 :             if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
                                              #  # ]
                                514                 :              0 :                 return PGRES_POLLING_WRITING;
                                515                 :                :             else
                                516                 :              0 :                 return PGRES_POLLING_FAILED;
                                517                 :                :         }
                                518                 :                : 
 1555 tgl@sss.pgh.pa.us         519         [ -  + ]:CBC         233 :         if (ret < amount)
                                520                 :                :         {
 1555 tgl@sss.pgh.pa.us         521                 :UBC           0 :             PqGSSSendNext += ret;
 1838 sfrost@snowman.net        522                 :              0 :             return PGRES_POLLING_WRITING;
                                523                 :                :         }
                                524                 :                : 
 1555 tgl@sss.pgh.pa.us         525                 :CBC         233 :         PqGSSSendLength = PqGSSSendNext = 0;
                                526                 :                :     }
                                527                 :                : 
                                528                 :                :     /*
                                529                 :                :      * Client sends first, and sending creates a context, therefore this will
                                530                 :                :      * be false the first time through, and then when we get called again we
                                531                 :                :      * will check for incoming data.
                                532                 :                :      */
 1838 sfrost@snowman.net        533         [ +  + ]:            698 :     if (conn->gctx)
                                534                 :                :     {
                                535                 :                :         /* Process any incoming data we might have */
                                536                 :                : 
                                537                 :                :         /* See if we are still trying to get the length */
                                538         [ +  - ]:            465 :         if (PqGSSRecvLength < sizeof(uint32))
                                539                 :                :         {
                                540                 :                :             /* Attempt to get the length first */
                                541                 :            465 :             result = gss_read(conn, PqGSSRecvBuffer + PqGSSRecvLength, sizeof(uint32) - PqGSSRecvLength, &ret);
                                542         [ +  + ]:            465 :             if (result != PGRES_POLLING_OK)
                                543                 :            232 :                 return result;
                                544                 :                : 
                                545                 :            233 :             PqGSSRecvLength += ret;
                                546                 :                : 
                                547         [ -  + ]:            233 :             if (PqGSSRecvLength < sizeof(uint32))
 1838 sfrost@snowman.net        548                 :UBC           0 :                 return PGRES_POLLING_READING;
                                549                 :                :         }
                                550                 :                : 
                                551                 :                :         /*
                                552                 :                :          * Check if we got an error packet
                                553                 :                :          *
                                554                 :                :          * This is safe to do because we shouldn't ever get a packet over 8192
                                555                 :                :          * and therefore the actual length bytes, being that they are in
                                556                 :                :          * network byte order, for any real packet will start with two zero
                                557                 :                :          * bytes.
                                558                 :                :          */
 1838 sfrost@snowman.net        559         [ -  + ]:CBC         233 :         if (PqGSSRecvBuffer[0] == 'E')
                                560                 :                :         {
                                561                 :                :             /*
                                562                 :                :              * For an error packet during startup, we don't get a length, so
                                563                 :                :              * simply read as much as we can fit into our buffer (as a string,
                                564                 :                :              * so leave a spot at the end for a NULL byte too) and report that
                                565                 :                :              * back to the caller.
                                566                 :                :              */
 1837 sfrost@snowman.net        567                 :UBC           0 :             result = gss_read(conn, PqGSSRecvBuffer + PqGSSRecvLength, PQ_GSS_RECV_BUFFER_SIZE - PqGSSRecvLength - 1, &ret);
 1838                           568         [ #  # ]:              0 :             if (result != PGRES_POLLING_OK)
                                569                 :              0 :                 return result;
                                570                 :                : 
                                571                 :              0 :             PqGSSRecvLength += ret;
                                572                 :                : 
  433 michael@paquier.xyz       573         [ #  # ]:              0 :             Assert(PqGSSRecvLength < PQ_GSS_RECV_BUFFER_SIZE);
                                574                 :              0 :             PqGSSRecvBuffer[PqGSSRecvLength] = '\0';
 1189 tgl@sss.pgh.pa.us         575                 :              0 :             appendPQExpBuffer(&conn->errorMessage, "%s\n", PqGSSRecvBuffer + 1);
                                576                 :                : 
 1838 sfrost@snowman.net        577                 :              0 :             return PGRES_POLLING_FAILED;
                                578                 :                :         }
                                579                 :                : 
                                580                 :                :         /*
                                581                 :                :          * We should have the whole length at this point, so pull it out and
                                582                 :                :          * then read whatever we have left of the packet
                                583                 :                :          */
                                584                 :                : 
                                585                 :                :         /* Get the length and check for over-length packet */
 1277 michael@paquier.xyz       586                 :CBC         233 :         input.length = pg_ntoh32(*(uint32 *) PqGSSRecvBuffer);
 1838 sfrost@snowman.net        587         [ -  + ]:            233 :         if (input.length > PQ_GSS_RECV_BUFFER_SIZE - sizeof(uint32))
                                588                 :                :         {
  516 peter@eisentraut.org      589                 :UBC           0 :             libpq_append_conn_error(conn, "oversize GSSAPI packet sent by the server (%zu > %zu)",
  331 tgl@sss.pgh.pa.us         590                 :              0 :                                     (size_t) input.length,
                                591                 :                :                                     PQ_GSS_RECV_BUFFER_SIZE - sizeof(uint32));
 1838 sfrost@snowman.net        592                 :              0 :             return PGRES_POLLING_FAILED;
                                593                 :                :         }
                                594                 :                : 
                                595                 :                :         /*
                                596                 :                :          * Read as much of the packet as we are able to on this call into
                                597                 :                :          * wherever we left off from the last time we were called.
                                598                 :                :          */
 1838 sfrost@snowman.net        599                 :CBC         233 :         result = gss_read(conn, PqGSSRecvBuffer + PqGSSRecvLength,
                                600                 :            233 :                           input.length - (PqGSSRecvLength - sizeof(uint32)), &ret);
                                601         [ -  + ]:            233 :         if (result != PGRES_POLLING_OK)
 1838 sfrost@snowman.net        602                 :UBC           0 :             return result;
                                603                 :                : 
 1838 sfrost@snowman.net        604                 :CBC         233 :         PqGSSRecvLength += ret;
                                605                 :                : 
                                606                 :                :         /*
                                607                 :                :          * If we got less than the rest of the packet then we need to return
                                608                 :                :          * and be called again.
                                609                 :                :          */
                                610         [ -  + ]:            233 :         if (PqGSSRecvLength - sizeof(uint32) < input.length)
 1838 sfrost@snowman.net        611                 :UBC           0 :             return PGRES_POLLING_READING;
                                612                 :                : 
 1838 sfrost@snowman.net        613                 :CBC         233 :         input.value = PqGSSRecvBuffer + sizeof(uint32);
                                614                 :                :     }
                                615                 :                : 
                                616                 :                :     /* Load the service name (no-op if already done */
                                617                 :            466 :     ret = pg_GSS_load_servicename(conn);
                                618         [ -  + ]:            466 :     if (ret != STATUS_OK)
 1838 sfrost@snowman.net        619                 :UBC           0 :         return PGRES_POLLING_FAILED;
                                620                 :                : 
  328 tgl@sss.pgh.pa.us         621   [ +  -  +  + ]:CBC         466 :     if (conn->gssdelegation && conn->gssdelegation[0] == '1')
                                622                 :                :     {
                                623                 :                :         /* Acquire credentials if possible */
  367 sfrost@snowman.net        624         [ -  + ]:             32 :         if (conn->gcred == GSS_C_NO_CREDENTIAL)
  367 sfrost@snowman.net        625                 :UBC           0 :             (void) pg_GSS_have_cred_cache(&conn->gcred);
                                626                 :                : 
                                627                 :                :         /*
                                628                 :                :          * We have credentials and gssdelegation is enabled, so request
                                629                 :                :          * credential delegation.  This may or may not actually result in
                                630                 :                :          * credentials being delegated- it depends on if the forwardable flag
                                631                 :                :          * has been set in the credential and if the server is configured to
                                632                 :                :          * accept delegated credentials.
                                633                 :                :          */
  367 sfrost@snowman.net        634         [ +  - ]:CBC          32 :         if (conn->gcred != GSS_C_NO_CREDENTIAL)
                                635                 :             32 :             gss_flags |= GSS_C_DELEG_FLAG;
                                636                 :                :     }
                                637                 :                : 
                                638                 :                :     /*
                                639                 :                :      * Call GSS init context, either with an empty input, or with a complete
                                640                 :                :      * packet from the server.
                                641                 :                :      */
 1838                           642                 :            466 :     major = gss_init_sec_context(&minor, conn->gcred, &conn->gctx,
                                643                 :                :                                  conn->gtarg_nam, GSS_C_NO_OID,
                                644                 :                :                                  gss_flags, 0, 0, &input, NULL,
                                645                 :                :                                  &output, NULL, NULL);
                                646                 :                : 
                                647                 :                :     /* GSS Init Sec Context uses the whole packet, so clear it */
 1555 tgl@sss.pgh.pa.us         648                 :            466 :     PqGSSRecvLength = 0;
                                649                 :                : 
 1838 sfrost@snowman.net        650         [ -  + ]:            466 :     if (GSS_ERROR(major))
                                651                 :                :     {
 1669 peter@eisentraut.org      652                 :UBC           0 :         pg_GSS_error(libpq_gettext("could not initiate GSSAPI security context"),
                                653                 :                :                      conn, major, minor);
 1838 sfrost@snowman.net        654                 :              0 :         return PGRES_POLLING_FAILED;
                                655                 :                :     }
                                656                 :                : 
 1555 tgl@sss.pgh.pa.us         657         [ +  + ]:CBC         466 :     if (output.length == 0)
                                658                 :                :     {
                                659                 :                :         /*
                                660                 :                :          * We're done - hooray!  Set flag to tell the low-level I/O routines
                                661                 :                :          * to do GSS wrapping/unwrapping.
                                662                 :                :          */
 1203                           663                 :            233 :         conn->gssenc = true;
  367 sfrost@snowman.net        664                 :            233 :         conn->gssapi_used = true;
                                665                 :                : 
                                666                 :                :         /* Clean up */
 1838                           667                 :            233 :         gss_release_cred(&minor, &conn->gcred);
                                668                 :            233 :         conn->gcred = GSS_C_NO_CREDENTIAL;
 1440 tgl@sss.pgh.pa.us         669                 :            233 :         gss_release_buffer(&minor, &output);
                                670                 :                : 
                                671                 :                :         /*
                                672                 :                :          * Determine the max packet size which will fit in our buffer, after
                                673                 :                :          * accounting for the length.  pg_GSS_write will need this.
                                674                 :                :          */
 1838 sfrost@snowman.net        675                 :            233 :         major = gss_wrap_size_limit(&minor, conn->gctx, 1, GSS_C_QOP_DEFAULT,
                                676                 :                :                                     PQ_GSS_SEND_BUFFER_SIZE - sizeof(uint32),
 1555 tgl@sss.pgh.pa.us         677                 :            233 :                                     &PqGSSMaxPktSize);
                                678                 :                : 
 1838 sfrost@snowman.net        679         [ -  + ]:            233 :         if (GSS_ERROR(major))
                                680                 :                :         {
 1838 sfrost@snowman.net        681                 :UBC           0 :             pg_GSS_error(libpq_gettext("GSSAPI size check error"), conn,
                                682                 :                :                          major, minor);
 1555 tgl@sss.pgh.pa.us         683                 :              0 :             return PGRES_POLLING_FAILED;
                                684                 :                :         }
                                685                 :                : 
 1838 sfrost@snowman.net        686                 :CBC         233 :         return PGRES_POLLING_OK;
                                687                 :                :     }
                                688                 :                : 
                                689                 :                :     /* Must have output.length > 0 */
                                690         [ -  + ]:            233 :     if (output.length > PQ_GSS_SEND_BUFFER_SIZE - sizeof(uint32))
                                691                 :                :     {
 1838 sfrost@snowman.net        692                 :UBC           0 :         pg_GSS_error(libpq_gettext("GSSAPI context establishment error"),
                                693                 :                :                      conn, major, minor);
 1440 tgl@sss.pgh.pa.us         694                 :              0 :         gss_release_buffer(&minor, &output);
 1838 sfrost@snowman.net        695                 :              0 :         return PGRES_POLLING_FAILED;
                                696                 :                :     }
                                697                 :                : 
                                698                 :                :     /* Queue the token for writing */
 1277 michael@paquier.xyz       699                 :CBC         233 :     netlen = pg_hton32(output.length);
                                700                 :                : 
 1838 sfrost@snowman.net        701                 :            233 :     memcpy(PqGSSSendBuffer, (char *) &netlen, sizeof(uint32));
 1555 tgl@sss.pgh.pa.us         702                 :            233 :     PqGSSSendLength += sizeof(uint32);
                                703                 :                : 
                                704                 :            233 :     memcpy(PqGSSSendBuffer + PqGSSSendLength, output.value, output.length);
                                705                 :            233 :     PqGSSSendLength += output.length;
                                706                 :                : 
                                707                 :                :     /* We don't bother with PqGSSSendConsumed here */
                                708                 :                : 
                                709                 :                :     /* Release buffer storage allocated by GSSAPI */
 1838 sfrost@snowman.net        710                 :            233 :     gss_release_buffer(&minor, &output);
                                711                 :                : 
                                712                 :                :     /* Ask to be called again to write data */
                                713                 :            233 :     return PGRES_POLLING_WRITING;
                                714                 :                : }
                                715                 :                : 
                                716                 :                : /*
                                717                 :                :  * GSSAPI Information functions.
                                718                 :                :  */
                                719                 :                : 
                                720                 :                : /*
                                721                 :                :  * Return the GSSAPI Context itself.
                                722                 :                :  */
                                723                 :                : void *
 1838 sfrost@snowman.net        724                 :UBC           0 : PQgetgssctx(PGconn *conn)
                                725                 :                : {
                                726         [ #  # ]:              0 :     if (!conn)
                                727                 :              0 :         return NULL;
                                728                 :                : 
                                729                 :              0 :     return conn->gctx;
                                730                 :                : }
                                731                 :                : 
                                732                 :                : /*
                                733                 :                :  * Return true if GSSAPI encryption is in use.
                                734                 :                :  */
                                735                 :                : int
 1838 sfrost@snowman.net        736                 :CBC           2 : PQgssEncInUse(PGconn *conn)
                                737                 :                : {
                                738   [ +  -  +  - ]:              2 :     if (!conn || !conn->gctx)
                                739                 :              2 :         return 0;
                                740                 :                : 
 1838 sfrost@snowman.net        741                 :UBC           0 :     return conn->gssenc;
                                742                 :                : }
        

Generated by: LCOV version 2.1-beta2-3-g6141622