LCOV - differential code coverage report
Current view: top level - src/backend/libpq - be-secure-gssapi.c (source / functions) Coverage Total Hit UBC CBC
Current: Differential Code Coverage 16@8cea358b128 vs 17@8cea358b128 Lines: 73.9 % 211 156 55 156
Current Date: 2024-04-14 14:21:10 Functions: 100.0 % 8 8 8
Baseline: 16@8cea358b128 Branches: 49.3 % 146 72 74 72
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: 73.2 % 205 150 55 150
Function coverage date bins:
(240..) days: 100.0 % 8 8 8
Branch coverage date bins:
(120,180] days: 50.0 % 6 3 3 3
(240..) days: 49.3 % 140 69 71 69

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * be-secure-gssapi.c
                                  4                 :                :  *  GSSAPI encryption support
                                  5                 :                :  *
                                  6                 :                :  * Portions Copyright (c) 2018-2024, PostgreSQL Global Development Group
                                  7                 :                :  *
                                  8                 :                :  * IDENTIFICATION
                                  9                 :                :  *  src/backend/libpq/be-secure-gssapi.c
                                 10                 :                :  *
                                 11                 :                :  *-------------------------------------------------------------------------
                                 12                 :                :  */
                                 13                 :                : 
                                 14                 :                : #include "postgres.h"
                                 15                 :                : 
                                 16                 :                : #include <unistd.h>
                                 17                 :                : 
                                 18                 :                : #include "libpq/auth.h"
                                 19                 :                : #include "libpq/be-gssapi-common.h"
                                 20                 :                : #include "libpq/libpq.h"
                                 21                 :                : #include "libpq/pqformat.h"
                                 22                 :                : #include "miscadmin.h"
                                 23                 :                : #include "pgstat.h"
                                 24                 :                : #include "utils/memutils.h"
                                 25                 :                : 
                                 26                 :                : 
                                 27                 :                : /*
                                 28                 :                :  * Handle the encryption/decryption of data using GSSAPI.
                                 29                 :                :  *
                                 30                 :                :  * In the encrypted data stream on the wire, we break up the data
                                 31                 :                :  * into packets where each packet starts with a uint32-size length
                                 32                 :                :  * word (in network byte order), then encrypted data of that length
                                 33                 :                :  * immediately following.  Decryption yields the same data stream
                                 34                 :                :  * that would appear when not using encryption.
                                 35                 :                :  *
                                 36                 :                :  * Encrypted data typically ends up being larger than the same data
                                 37                 :                :  * unencrypted, so we use fixed-size buffers for handling the
                                 38                 :                :  * encryption/decryption which are larger than PQComm's buffer will
                                 39                 :                :  * typically be to minimize the times where we have to make multiple
                                 40                 :                :  * packets (and therefore multiple recv/send calls for a single
                                 41                 :                :  * read/write call to us).
                                 42                 :                :  *
                                 43                 :                :  * NOTE: The client and server have to agree on the max packet size,
                                 44                 :                :  * because we have to pass an entire packet to GSSAPI at a time and we
                                 45                 :                :  * don't want the other side to send arbitrarily huge packets as we
                                 46                 :                :  * would have to allocate memory for them to then pass them to GSSAPI.
                                 47                 :                :  *
                                 48                 :                :  * Therefore, these two #define's are effectively part of the protocol
                                 49                 :                :  * spec and can't ever be changed.
                                 50                 :                :  */
                                 51                 :                : #define PQ_GSS_SEND_BUFFER_SIZE 16384
                                 52                 :                : #define PQ_GSS_RECV_BUFFER_SIZE 16384
                                 53                 :                : 
                                 54                 :                : /*
                                 55                 :                :  * Since we manage at most one GSS-encrypted connection per backend,
                                 56                 :                :  * we can just keep all this state in static variables.  The char *
                                 57                 :                :  * variables point to buffers that are allocated once and re-used.
                                 58                 :                :  */
                                 59                 :                : static char *PqGSSSendBuffer;   /* Encrypted data waiting to be sent */
                                 60                 :                : static int  PqGSSSendLength;    /* End of data available in PqGSSSendBuffer */
                                 61                 :                : static int  PqGSSSendNext;      /* Next index to send a byte from
                                 62                 :                :                                  * PqGSSSendBuffer */
                                 63                 :                : static int  PqGSSSendConsumed;  /* Number of source bytes encrypted but not
                                 64                 :                :                                  * yet reported as sent */
                                 65                 :                : 
                                 66                 :                : static char *PqGSSRecvBuffer;   /* Received, encrypted data */
                                 67                 :                : static int  PqGSSRecvLength;    /* End of data available in PqGSSRecvBuffer */
                                 68                 :                : 
                                 69                 :                : static char *PqGSSResultBuffer; /* Decryption of data in gss_RecvBuffer */
                                 70                 :                : static int  PqGSSResultLength;  /* End of data available in PqGSSResultBuffer */
                                 71                 :                : static int  PqGSSResultNext;    /* Next index to read a byte from
                                 72                 :                :                                  * PqGSSResultBuffer */
                                 73                 :                : 
                                 74                 :                : static uint32 PqGSSMaxPktSize;  /* Maximum size we can encrypt and fit the
                                 75                 :                :                                  * results into our output buffer */
                                 76                 :                : 
                                 77                 :                : 
                                 78                 :                : /*
                                 79                 :                :  * Attempt to write len bytes of data from ptr to a GSSAPI-encrypted connection.
                                 80                 :                :  *
                                 81                 :                :  * The connection must be already set up for GSSAPI encryption (i.e., GSSAPI
                                 82                 :                :  * transport negotiation is complete).
                                 83                 :                :  *
                                 84                 :                :  * On success, returns the number of data bytes consumed (possibly less than
                                 85                 :                :  * len).  On failure, returns -1 with errno set appropriately.  For retryable
                                 86                 :                :  * errors, caller should call again (passing the same or more data) once the
                                 87                 :                :  * socket is ready.
                                 88                 :                :  *
                                 89                 :                :  * Dealing with fatal errors here is a bit tricky: we can't invoke elog(FATAL)
                                 90                 :                :  * since it would try to write to the client, probably resulting in infinite
                                 91                 :                :  * recursion.  Instead, use elog(COMMERROR) to log extra info about the
                                 92                 :                :  * failure if necessary, and then return an errno indicating connection loss.
                                 93                 :                :  */
                                 94                 :                : ssize_t
 1838 sfrost@snowman.net         95                 :CBC         596 : be_gssapi_write(Port *port, void *ptr, size_t len)
                                 96                 :                : {
                                 97                 :                :     OM_uint32   major,
                                 98                 :                :                 minor;
                                 99                 :                :     gss_buffer_desc input,
                                100                 :                :                 output;
                                101                 :                :     size_t      bytes_to_encrypt;
                                102                 :                :     size_t      bytes_encrypted;
 1555 tgl@sss.pgh.pa.us         103                 :            596 :     gss_ctx_id_t gctx = port->gss->ctx;
                                104                 :                : 
                                105                 :                :     /*
                                106                 :                :      * When we get a retryable failure, we must not tell the caller we have
                                107                 :                :      * successfully transmitted everything, else it won't retry.  For
                                108                 :                :      * simplicity, we claim we haven't transmitted anything until we have
                                109                 :                :      * successfully transmitted all "len" bytes.  Between calls, the amount of
                                110                 :                :      * the current input data that's already been encrypted and placed into
                                111                 :                :      * PqGSSSendBuffer (and perhaps transmitted) is remembered in
                                112                 :                :      * PqGSSSendConsumed.  On a retry, the caller *must* be sending that data
                                113                 :                :      * again, so if it offers a len less than that, something is wrong.
                                114                 :                :      *
                                115                 :                :      * Note: it may seem attractive to report partial write completion once
                                116                 :                :      * we've successfully sent any encrypted packets.  However, that can cause
                                117                 :                :      * problems for callers; notably, pqPutMsgEnd's heuristic to send only
                                118                 :                :      * full 8K blocks interacts badly with such a hack.  We won't save much,
                                119                 :                :      * typically, by letting callers discard data early, so don't risk it.
                                120                 :                :      */
                                121         [ -  + ]:            596 :     if (len < PqGSSSendConsumed)
                                122                 :                :     {
 1203 tgl@sss.pgh.pa.us         123         [ #  # ]:UBC           0 :         elog(COMMERROR, "GSSAPI caller failed to retransmit all data needing to be retried");
                                124                 :              0 :         errno = ECONNRESET;
                                125                 :              0 :         return -1;
                                126                 :                :     }
                                127                 :                : 
                                128                 :                :     /* Discount whatever source data we already encrypted. */
 1555 tgl@sss.pgh.pa.us         129                 :CBC         596 :     bytes_to_encrypt = len - PqGSSSendConsumed;
                                130                 :            596 :     bytes_encrypted = PqGSSSendConsumed;
                                131                 :                : 
                                132                 :                :     /*
                                133                 :                :      * Loop through encrypting data and sending it out until it's all done or
                                134                 :                :      * secure_raw_write() complains (which would likely mean that the socket
                                135                 :                :      * is non-blocking and the requested send() would block, or there was some
                                136                 :                :      * kind of actual error).
                                137                 :                :      */
                                138   [ +  +  +  - ]:           1192 :     while (bytes_to_encrypt || PqGSSSendLength)
                                139                 :                :     {
 1669 peter@eisentraut.org      140                 :           1192 :         int         conf_state = 0;
                                141                 :                :         uint32      netlen;
                                142                 :                : 
                                143                 :                :         /*
                                144                 :                :          * Check if we have data in the encrypted output buffer that needs to
                                145                 :                :          * be sent (possibly left over from a previous call), and if so, try
                                146                 :                :          * to send it.  If we aren't able to, return that fact back up to the
                                147                 :                :          * caller.
                                148                 :                :          */
 1555 tgl@sss.pgh.pa.us         149         [ +  + ]:           1192 :         if (PqGSSSendLength)
                                150                 :                :         {
                                151                 :                :             ssize_t     ret;
                                152                 :            596 :             ssize_t     amount = PqGSSSendLength - PqGSSSendNext;
                                153                 :                : 
                                154                 :            596 :             ret = secure_raw_write(port, PqGSSSendBuffer + PqGSSSendNext, amount);
 1838 sfrost@snowman.net        155         [ -  + ]:            596 :             if (ret <= 0)
 1555 tgl@sss.pgh.pa.us         156                 :UBC           0 :                 return ret;
                                157                 :                : 
                                158                 :                :             /*
                                159                 :                :              * Check if this was a partial write, and if so, move forward that
                                160                 :                :              * far in our buffer and try again.
                                161                 :                :              */
  143 tgl@sss.pgh.pa.us         162         [ -  + ]:CBC         596 :             if (ret < amount)
                                163                 :                :             {
 1555 tgl@sss.pgh.pa.us         164                 :UBC           0 :                 PqGSSSendNext += ret;
 1838 sfrost@snowman.net        165                 :              0 :                 continue;
                                166                 :                :             }
                                167                 :                : 
                                168                 :                :             /* We've successfully sent whatever data was in the buffer. */
  143 tgl@sss.pgh.pa.us         169                 :CBC         596 :             PqGSSSendLength = PqGSSSendNext = 0;
                                170                 :                :         }
                                171                 :                : 
                                172                 :                :         /*
                                173                 :                :          * Check if there are any bytes left to encrypt.  If not, we're done.
                                174                 :                :          */
 1838 sfrost@snowman.net        175         [ +  + ]:           1192 :         if (!bytes_to_encrypt)
 1555 tgl@sss.pgh.pa.us         176                 :            596 :             break;
                                177                 :                : 
                                178                 :                :         /*
                                179                 :                :          * Check how much we are being asked to send, if it's too much, then
                                180                 :                :          * we will have to loop and possibly be called multiple times to get
                                181                 :                :          * through all the data.
                                182                 :                :          */
                                183         [ -  + ]:            596 :         if (bytes_to_encrypt > PqGSSMaxPktSize)
 1555 tgl@sss.pgh.pa.us         184                 :UBC           0 :             input.length = PqGSSMaxPktSize;
                                185                 :                :         else
 1838 sfrost@snowman.net        186                 :CBC         596 :             input.length = bytes_to_encrypt;
                                187                 :                : 
                                188                 :            596 :         input.value = (char *) ptr + bytes_encrypted;
                                189                 :                : 
                                190                 :            596 :         output.value = NULL;
                                191                 :            596 :         output.length = 0;
                                192                 :                : 
                                193                 :                :         /*
                                194                 :                :          * Create the next encrypted packet.  Any failure here is considered a
                                195                 :                :          * hard failure, so we return -1 even if some data has been sent.
                                196                 :                :          */
 1555 tgl@sss.pgh.pa.us         197                 :            596 :         major = gss_wrap(&minor, gctx, 1, GSS_C_QOP_DEFAULT,
                                198                 :                :                          &input, &conf_state, &output);
 1838 sfrost@snowman.net        199         [ -  + ]:            596 :         if (major != GSS_S_COMPLETE)
                                200                 :                :         {
 1203 tgl@sss.pgh.pa.us         201                 :UBC           0 :             pg_GSS_error(_("GSSAPI wrap error"), major, minor);
                                202                 :              0 :             errno = ECONNRESET;
                                203                 :              0 :             return -1;
                                204                 :                :         }
 1669 peter@eisentraut.org      205         [ -  + ]:CBC         596 :         if (conf_state == 0)
                                206                 :                :         {
 1203 tgl@sss.pgh.pa.us         207         [ #  # ]:UBC           0 :             ereport(COMMERROR,
                                208                 :                :                     (errmsg("outgoing GSSAPI message would not use confidentiality")));
                                209                 :              0 :             errno = ECONNRESET;
                                210                 :              0 :             return -1;
                                211                 :                :         }
 1838 sfrost@snowman.net        212         [ -  + ]:CBC         596 :         if (output.length > PQ_GSS_SEND_BUFFER_SIZE - sizeof(uint32))
                                213                 :                :         {
 1203 tgl@sss.pgh.pa.us         214         [ #  # ]:UBC           0 :             ereport(COMMERROR,
                                215                 :                :                     (errmsg("server tried to send oversize GSSAPI packet (%zu > %zu)",
                                216                 :                :                             (size_t) output.length,
                                217                 :                :                             PQ_GSS_SEND_BUFFER_SIZE - sizeof(uint32))));
                                218                 :              0 :             errno = ECONNRESET;
                                219                 :              0 :             return -1;
                                220                 :                :         }
                                221                 :                : 
 1838 sfrost@snowman.net        222                 :CBC         596 :         bytes_encrypted += input.length;
                                223                 :            596 :         bytes_to_encrypt -= input.length;
 1555 tgl@sss.pgh.pa.us         224                 :            596 :         PqGSSSendConsumed += input.length;
                                225                 :                : 
                                226                 :                :         /* 4 network-order bytes of length, then payload */
 1277 michael@paquier.xyz       227                 :            596 :         netlen = pg_hton32(output.length);
 1555 tgl@sss.pgh.pa.us         228                 :            596 :         memcpy(PqGSSSendBuffer + PqGSSSendLength, &netlen, sizeof(uint32));
                                229                 :            596 :         PqGSSSendLength += sizeof(uint32);
                                230                 :                : 
                                231                 :            596 :         memcpy(PqGSSSendBuffer + PqGSSSendLength, output.value, output.length);
                                232                 :            596 :         PqGSSSendLength += output.length;
                                233                 :                : 
                                234                 :                :         /* Release buffer storage allocated by GSSAPI */
 1440                           235                 :            596 :         gss_release_buffer(&minor, &output);
                                236                 :                :     }
                                237                 :                : 
                                238                 :                :     /* If we get here, our counters should all match up. */
  143                           239         [ -  + ]:            596 :     Assert(len == PqGSSSendConsumed);
                                240         [ -  + ]:            596 :     Assert(len == bytes_encrypted);
                                241                 :                : 
                                242                 :                :     /* We're reporting all the data as sent, so reset PqGSSSendConsumed. */
                                243                 :            596 :     PqGSSSendConsumed = 0;
                                244                 :                : 
                                245                 :            596 :     return bytes_encrypted;
                                246                 :                : }
                                247                 :                : 
                                248                 :                : /*
                                249                 :                :  * Read up to len bytes of data into ptr from a GSSAPI-encrypted connection.
                                250                 :                :  *
                                251                 :                :  * The connection must be already set up for GSSAPI encryption (i.e., GSSAPI
                                252                 :                :  * transport negotiation is complete).
                                253                 :                :  *
                                254                 :                :  * Returns the number of data bytes read, or on failure, returns -1
                                255                 :                :  * with errno set appropriately.  For retryable errors, caller should call
                                256                 :                :  * again once the socket is ready.
                                257                 :                :  *
                                258                 :                :  * We treat fatal errors the same as in be_gssapi_write(), even though the
                                259                 :                :  * argument about infinite recursion doesn't apply here.
                                260                 :                :  */
                                261                 :                : ssize_t
 1838 sfrost@snowman.net        262                 :           1244 : be_gssapi_read(Port *port, void *ptr, size_t len)
                                263                 :                : {
                                264                 :                :     OM_uint32   major,
                                265                 :                :                 minor;
                                266                 :                :     gss_buffer_desc input,
                                267                 :                :                 output;
                                268                 :                :     ssize_t     ret;
                                269                 :           1244 :     size_t      bytes_returned = 0;
 1555 tgl@sss.pgh.pa.us         270                 :           1244 :     gss_ctx_id_t gctx = port->gss->ctx;
                                271                 :                : 
                                272                 :                :     /*
                                273                 :                :      * The plan here is to read one incoming encrypted packet into
                                274                 :                :      * PqGSSRecvBuffer, decrypt it into PqGSSResultBuffer, and then dole out
                                275                 :                :      * data from there to the caller.  When we exhaust the current input
                                276                 :                :      * packet, read another.
                                277                 :                :      */
                                278         [ +  - ]:           1862 :     while (bytes_returned < len)
                                279                 :                :     {
                                280                 :           1862 :         int         conf_state = 0;
                                281                 :                : 
                                282                 :                :         /* Check if we have data in our buffer that we can return immediately */
                                283         [ +  + ]:           1862 :         if (PqGSSResultNext < PqGSSResultLength)
                                284                 :                :         {
                                285                 :            618 :             size_t      bytes_in_buffer = PqGSSResultLength - PqGSSResultNext;
                                286                 :            618 :             size_t      bytes_to_copy = Min(bytes_in_buffer, len - bytes_returned);
                                287                 :                : 
                                288                 :                :             /*
                                289                 :                :              * Copy the data from our result buffer into the caller's buffer,
                                290                 :                :              * at the point where we last left off filling their buffer.
                                291                 :                :              */
                                292                 :            618 :             memcpy((char *) ptr + bytes_returned, PqGSSResultBuffer + PqGSSResultNext, bytes_to_copy);
                                293                 :            618 :             PqGSSResultNext += bytes_to_copy;
 1838 sfrost@snowman.net        294                 :            618 :             bytes_returned += bytes_to_copy;
                                295                 :                : 
                                296                 :                :             /*
                                297                 :                :              * At this point, we've either filled the caller's buffer or
                                298                 :                :              * emptied our result buffer.  Either way, return to caller.  In
                                299                 :                :              * the second case, we could try to read another encrypted packet,
                                300                 :                :              * but the odds are good that there isn't one available.  (If this
                                301                 :                :              * isn't true, we chose too small a max packet size.)  In any
                                302                 :                :              * case, there's no harm letting the caller process the data we've
                                303                 :                :              * already returned.
                                304                 :                :              */
 1555 tgl@sss.pgh.pa.us         305                 :            618 :             break;
                                306                 :                :         }
                                307                 :                : 
                                308                 :                :         /* Result buffer is empty, so reset buffer pointers */
                                309                 :           1244 :         PqGSSResultLength = PqGSSResultNext = 0;
                                310                 :                : 
                                311                 :                :         /*
                                312                 :                :          * Because we chose above to return immediately as soon as we emit
                                313                 :                :          * some data, bytes_returned must be zero at this point.  Therefore
                                314                 :                :          * the failure exits below can just return -1 without worrying about
                                315                 :                :          * whether we already emitted some data.
                                316                 :                :          */
                                317         [ -  + ]:           1244 :         Assert(bytes_returned == 0);
                                318                 :                : 
                                319                 :                :         /*
                                320                 :                :          * At this point, our result buffer is empty with more bytes being
                                321                 :                :          * requested to be read.  We are now ready to load the next packet and
                                322                 :                :          * decrypt it (entirely) into our result buffer.
                                323                 :                :          */
                                324                 :                : 
                                325                 :                :         /* Collect the length if we haven't already */
 1838 sfrost@snowman.net        326         [ +  + ]:           1244 :         if (PqGSSRecvLength < sizeof(uint32))
                                327                 :                :         {
                                328                 :           1241 :             ret = secure_raw_read(port, PqGSSRecvBuffer + PqGSSRecvLength,
                                329                 :                :                                   sizeof(uint32) - PqGSSRecvLength);
                                330                 :                : 
                                331                 :                :             /* If ret <= 0, secure_raw_read already set the correct errno */
 1555 tgl@sss.pgh.pa.us         332         [ +  + ]:           1241 :             if (ret <= 0)
                                333                 :            626 :                 return ret;
                                334                 :                : 
 1838 sfrost@snowman.net        335                 :            618 :             PqGSSRecvLength += ret;
                                336                 :                : 
                                337                 :                :             /* If we still haven't got the length, return to the caller */
                                338         [ -  + ]:            618 :             if (PqGSSRecvLength < sizeof(uint32))
                                339                 :                :             {
 1555 tgl@sss.pgh.pa.us         340                 :UBC           0 :                 errno = EWOULDBLOCK;
                                341                 :              0 :                 return -1;
                                342                 :                :             }
                                343                 :                :         }
                                344                 :                : 
                                345                 :                :         /* Decode the packet length and check for overlength packet */
 1277 michael@paquier.xyz       346                 :CBC         621 :         input.length = pg_ntoh32(*(uint32 *) PqGSSRecvBuffer);
                                347                 :                : 
 1838 sfrost@snowman.net        348         [ -  + ]:            621 :         if (input.length > PQ_GSS_RECV_BUFFER_SIZE - sizeof(uint32))
                                349                 :                :         {
 1203 tgl@sss.pgh.pa.us         350         [ #  # ]:UBC           0 :             ereport(COMMERROR,
                                351                 :                :                     (errmsg("oversize GSSAPI packet sent by the client (%zu > %zu)",
                                352                 :                :                             (size_t) input.length,
                                353                 :                :                             PQ_GSS_RECV_BUFFER_SIZE - sizeof(uint32))));
                                354                 :              0 :             errno = ECONNRESET;
                                355                 :              0 :             return -1;
                                356                 :                :         }
                                357                 :                : 
                                358                 :                :         /*
                                359                 :                :          * Read as much of the packet as we are able to on this call into
                                360                 :                :          * wherever we left off from the last time we were called.
                                361                 :                :          */
 1838 sfrost@snowman.net        362                 :CBC         621 :         ret = secure_raw_read(port, PqGSSRecvBuffer + PqGSSRecvLength,
                                363                 :            621 :                               input.length - (PqGSSRecvLength - sizeof(uint32)));
                                364                 :                :         /* If ret <= 0, secure_raw_read already set the correct errno */
 1555 tgl@sss.pgh.pa.us         365         [ -  + ]:            621 :         if (ret <= 0)
 1555 tgl@sss.pgh.pa.us         366                 :UBC           0 :             return ret;
                                367                 :                : 
 1838 sfrost@snowman.net        368                 :CBC         621 :         PqGSSRecvLength += ret;
                                369                 :                : 
                                370                 :                :         /* If we don't yet have the whole packet, return to the caller */
                                371         [ +  + ]:            621 :         if (PqGSSRecvLength - sizeof(uint32) < input.length)
                                372                 :                :         {
 1555 tgl@sss.pgh.pa.us         373                 :              3 :             errno = EWOULDBLOCK;
                                374                 :              3 :             return -1;
                                375                 :                :         }
                                376                 :                : 
                                377                 :                :         /*
                                378                 :                :          * We now have the full packet and we can perform the decryption and
                                379                 :                :          * refill our result buffer, then loop back up to pass data back to
                                380                 :                :          * the caller.
                                381                 :                :          */
 1838 sfrost@snowman.net        382                 :            618 :         output.value = NULL;
                                383                 :            618 :         output.length = 0;
                                384                 :            618 :         input.value = PqGSSRecvBuffer + sizeof(uint32);
                                385                 :                : 
 1555 tgl@sss.pgh.pa.us         386                 :            618 :         major = gss_unwrap(&minor, gctx, &input, &output, &conf_state, NULL);
 1838 sfrost@snowman.net        387         [ -  + ]:            618 :         if (major != GSS_S_COMPLETE)
                                388                 :                :         {
 1203 tgl@sss.pgh.pa.us         389                 :UBC           0 :             pg_GSS_error(_("GSSAPI unwrap error"), major, minor);
                                390                 :              0 :             errno = ECONNRESET;
                                391                 :              0 :             return -1;
                                392                 :                :         }
 1669 peter@eisentraut.org      393         [ -  + ]:CBC         618 :         if (conf_state == 0)
                                394                 :                :         {
 1203 tgl@sss.pgh.pa.us         395         [ #  # ]:UBC           0 :             ereport(COMMERROR,
                                396                 :                :                     (errmsg("incoming GSSAPI message did not use confidentiality")));
                                397                 :              0 :             errno = ECONNRESET;
                                398                 :              0 :             return -1;
                                399                 :                :         }
                                400                 :                : 
 1838 sfrost@snowman.net        401                 :CBC         618 :         memcpy(PqGSSResultBuffer, output.value, output.length);
                                402                 :            618 :         PqGSSResultLength = output.length;
                                403                 :                : 
                                404                 :                :         /* Our receive buffer is now empty, reset it */
                                405                 :            618 :         PqGSSRecvLength = 0;
                                406                 :                : 
                                407                 :                :         /* Release buffer storage allocated by GSSAPI */
                                408                 :            618 :         gss_release_buffer(&minor, &output);
                                409                 :                :     }
                                410                 :                : 
                                411                 :            618 :     return bytes_returned;
                                412                 :                : }
                                413                 :                : 
                                414                 :                : /*
                                415                 :                :  * Read the specified number of bytes off the wire, waiting using
                                416                 :                :  * WaitLatchOrSocket if we would block.
                                417                 :                :  *
                                418                 :                :  * Results are read into PqGSSRecvBuffer.
                                419                 :                :  *
                                420                 :                :  * Will always return either -1, to indicate a permanent error, or len.
                                421                 :                :  */
                                422                 :                : static ssize_t
                                423                 :            464 : read_or_wait(Port *port, ssize_t len)
                                424                 :                : {
                                425                 :                :     ssize_t     ret;
                                426                 :                : 
                                427                 :                :     /*
                                428                 :                :      * Keep going until we either read in everything we were asked to, or we
                                429                 :                :      * error out.
                                430                 :                :      */
 1555 tgl@sss.pgh.pa.us         431         [ +  + ]:           1160 :     while (PqGSSRecvLength < len)
                                432                 :                :     {
 1838 sfrost@snowman.net        433                 :            696 :         ret = secure_raw_read(port, PqGSSRecvBuffer + PqGSSRecvLength, len - PqGSSRecvLength);
                                434                 :                : 
                                435                 :                :         /*
                                436                 :                :          * If we got back an error and it wasn't just
                                437                 :                :          * EWOULDBLOCK/EAGAIN/EINTR, then give up.
                                438                 :                :          */
 1555 tgl@sss.pgh.pa.us         439         [ +  + ]:            696 :         if (ret < 0 &&
                                440   [ -  +  -  -  :            232 :             !(errno == EWOULDBLOCK || errno == EAGAIN || errno == EINTR))
                                              -  - ]
 1838 sfrost@snowman.net        441                 :UBC           0 :             return -1;
                                442                 :                : 
                                443                 :                :         /*
                                444                 :                :          * Ok, we got back either a positive value, zero, or a negative result
                                445                 :                :          * indicating we should retry.
                                446                 :                :          *
                                447                 :                :          * If it was zero or negative, then we wait on the socket to be
                                448                 :                :          * readable again.
                                449                 :                :          */
 1838 sfrost@snowman.net        450         [ +  + ]:CBC         696 :         if (ret <= 0)
                                451                 :                :         {
                                452                 :            232 :             WaitLatchOrSocket(MyLatch,
                                453                 :                :                               WL_SOCKET_READABLE | WL_EXIT_ON_PM_DEATH,
                                454                 :                :                               port->sock, 0, WAIT_EVENT_GSS_OPEN_SERVER);
                                455                 :                : 
                                456                 :                :             /*
                                457                 :                :              * If we got back zero bytes, and then waited on the socket to be
                                458                 :                :              * readable and got back zero bytes on a second read, then this is
                                459                 :                :              * EOF and the client hung up on us.
                                460                 :                :              *
                                461                 :                :              * If we did get data here, then we can just fall through and
                                462                 :                :              * handle it just as if we got data the first time.
                                463                 :                :              *
                                464                 :                :              * Otherwise loop back to the top and try again.
                                465                 :                :              */
                                466         [ -  + ]:            232 :             if (ret == 0)
                                467                 :                :             {
 1838 sfrost@snowman.net        468                 :UBC           0 :                 ret = secure_raw_read(port, PqGSSRecvBuffer + PqGSSRecvLength, len - PqGSSRecvLength);
                                469         [ #  # ]:              0 :                 if (ret == 0)
                                470                 :              0 :                     return -1;
                                471                 :                :             }
 1555 tgl@sss.pgh.pa.us         472         [ +  - ]:CBC         232 :             if (ret < 0)
 1838 sfrost@snowman.net        473                 :            232 :                 continue;
                                474                 :                :         }
                                475                 :                : 
                                476                 :            464 :         PqGSSRecvLength += ret;
                                477                 :                :     }
                                478                 :                : 
                                479                 :            464 :     return len;
                                480                 :                : }
                                481                 :                : 
                                482                 :                : /*
                                483                 :                :  * Start up a GSSAPI-encrypted connection.  This performs GSSAPI
                                484                 :                :  * authentication; after this function completes, it is safe to call
                                485                 :                :  * be_gssapi_read and be_gssapi_write.  Returns -1 and logs on failure;
                                486                 :                :  * otherwise, returns 0 and marks the connection as ready for GSSAPI
                                487                 :                :  * encryption.
                                488                 :                :  *
                                489                 :                :  * Note that unlike the be_gssapi_read/be_gssapi_write functions, this
                                490                 :                :  * function WILL block on the socket to be ready for read/write (using
                                491                 :                :  * WaitLatchOrSocket) as appropriate while establishing the GSSAPI
                                492                 :                :  * session.
                                493                 :                :  */
                                494                 :                : ssize_t
                                495                 :            232 : secure_open_gssapi(Port *port)
                                496                 :                : {
                                497                 :            232 :     bool        complete_next = false;
                                498                 :                :     OM_uint32   major,
                                499                 :                :                 minor;
                                500                 :                :     gss_cred_id_t delegated_creds;
                                501                 :                : 
                                502                 :                :     /*
                                503                 :                :      * Allocate subsidiary Port data for GSSAPI operations.
                                504                 :                :      */
 1203 tgl@sss.pgh.pa.us         505                 :            232 :     port->gss = (pg_gssinfo *)
                                506                 :            232 :         MemoryContextAllocZero(TopMemoryContext, sizeof(pg_gssinfo));
                                507                 :                : 
  367 sfrost@snowman.net        508                 :            232 :     delegated_creds = GSS_C_NO_CREDENTIAL;
                                509                 :            232 :     port->gss->delegated_creds = false;
                                510                 :                : 
                                511                 :                :     /*
                                512                 :                :      * Allocate buffers and initialize state variables.  By malloc'ing the
                                513                 :                :      * buffers at this point, we avoid wasting static data space in processes
                                514                 :                :      * that will never use them, and we ensure that the buffers are
                                515                 :                :      * sufficiently aligned for the length-word accesses that we do in some
                                516                 :                :      * places in this file.
                                517                 :                :      */
 1555 tgl@sss.pgh.pa.us         518                 :            232 :     PqGSSSendBuffer = malloc(PQ_GSS_SEND_BUFFER_SIZE);
                                519                 :            232 :     PqGSSRecvBuffer = malloc(PQ_GSS_RECV_BUFFER_SIZE);
                                520                 :            232 :     PqGSSResultBuffer = malloc(PQ_GSS_RECV_BUFFER_SIZE);
                                521   [ +  -  +  -  :            232 :     if (!PqGSSSendBuffer || !PqGSSRecvBuffer || !PqGSSResultBuffer)
                                              -  + ]
 1555 tgl@sss.pgh.pa.us         522         [ #  # ]:UBC           0 :         ereport(FATAL,
                                523                 :                :                 (errcode(ERRCODE_OUT_OF_MEMORY),
                                524                 :                :                  errmsg("out of memory")));
 1555 tgl@sss.pgh.pa.us         525                 :CBC         232 :     PqGSSSendLength = PqGSSSendNext = PqGSSSendConsumed = 0;
                                526                 :            232 :     PqGSSRecvLength = PqGSSResultLength = PqGSSResultNext = 0;
                                527                 :                : 
                                528                 :                :     /*
                                529                 :                :      * Use the configured keytab, if there is one.  As we now require MIT
                                530                 :                :      * Kerberos, we might consider using the credential store extensions in
                                531                 :                :      * the future instead of the environment variable.
                                532                 :                :      */
 1201                           533   [ -  +  -  + ]:            232 :     if (pg_krb_server_keyfile != NULL && pg_krb_server_keyfile[0] != '\0')
                                534                 :                :     {
                                535         [ +  - ]:            232 :         if (setenv("KRB5_KTNAME", pg_krb_server_keyfile, 1) != 0)
                                536                 :                :         {
                                537                 :                :             /* The only likely failure cause is OOM, so use that errcode */
 1201 tgl@sss.pgh.pa.us         538         [ #  # ]:UBC           0 :             ereport(FATAL,
                                539                 :                :                     (errcode(ERRCODE_OUT_OF_MEMORY),
                                540                 :                :                      errmsg("could not set environment: %m")));
                                541                 :                :         }
                                542                 :                :     }
                                543                 :                : 
                                544                 :                :     while (true)
 1838 sfrost@snowman.net        545                 :              0 :     {
                                546                 :                :         ssize_t     ret;
                                547                 :                :         gss_buffer_desc input,
 1838 sfrost@snowman.net        548                 :CBC         232 :                     output = GSS_C_EMPTY_BUFFER;
                                549                 :                : 
                                550                 :                :         /*
                                551                 :                :          * The client always sends first, so try to go ahead and read the
                                552                 :                :          * length and wait on the socket to be readable again if that fails.
                                553                 :                :          */
                                554                 :            232 :         ret = read_or_wait(port, sizeof(uint32));
                                555         [ -  + ]:            232 :         if (ret < 0)
 1838 sfrost@snowman.net        556                 :UBC           0 :             return ret;
                                557                 :                : 
                                558                 :                :         /*
                                559                 :                :          * Get the length for this packet from the length header.
                                560                 :                :          */
 1277 michael@paquier.xyz       561                 :CBC         232 :         input.length = pg_ntoh32(*(uint32 *) PqGSSRecvBuffer);
                                562                 :                : 
                                563                 :                :         /* Done with the length, reset our buffer */
 1838 sfrost@snowman.net        564                 :            232 :         PqGSSRecvLength = 0;
                                565                 :                : 
                                566                 :                :         /*
                                567                 :                :          * During initialization, packets are always fully consumed and
                                568                 :                :          * shouldn't ever be over PQ_GSS_RECV_BUFFER_SIZE in length.
                                569                 :                :          *
                                570                 :                :          * Verify on our side that the client doesn't do something funny.
                                571                 :                :          */
                                572         [ -  + ]:            232 :         if (input.length > PQ_GSS_RECV_BUFFER_SIZE)
                                573                 :                :         {
 1203 tgl@sss.pgh.pa.us         574         [ #  # ]:UBC           0 :             ereport(COMMERROR,
                                575                 :                :                     (errmsg("oversize GSSAPI packet sent by the client (%zu > %d)",
                                576                 :                :                             (size_t) input.length,
                                577                 :                :                             PQ_GSS_RECV_BUFFER_SIZE)));
                                578                 :              0 :             return -1;
                                579                 :                :         }
                                580                 :                : 
                                581                 :                :         /*
                                582                 :                :          * Get the rest of the packet so we can pass it to GSSAPI to accept
                                583                 :                :          * the context.
                                584                 :                :          */
 1838 sfrost@snowman.net        585                 :CBC         232 :         ret = read_or_wait(port, input.length);
                                586         [ -  + ]:            232 :         if (ret < 0)
 1838 sfrost@snowman.net        587                 :UBC           0 :             return ret;
                                588                 :                : 
 1838 sfrost@snowman.net        589                 :CBC         232 :         input.value = PqGSSRecvBuffer;
                                590                 :                : 
                                591                 :                :         /* Process incoming data.  (The client sends first.) */
                                592                 :            232 :         major = gss_accept_sec_context(&minor, &port->gss->ctx,
                                593                 :                :                                        GSS_C_NO_CREDENTIAL, &input,
                                594                 :                :                                        GSS_C_NO_CHANNEL_BINDINGS,
                                595                 :            232 :                                        &port->gss->name, NULL, &output, NULL,
  330 bruce@momjian.us          596         [ +  + ]:            232 :                                        NULL, pg_gss_accept_delegation ? &delegated_creds : NULL);
                                597                 :                : 
 1838 sfrost@snowman.net        598         [ -  + ]:            232 :         if (GSS_ERROR(major))
                                599                 :                :         {
 1203 tgl@sss.pgh.pa.us         600                 :UBC           0 :             pg_GSS_error(_("could not accept GSSAPI security context"),
                                601                 :                :                          major, minor);
 1838 sfrost@snowman.net        602                 :              0 :             gss_release_buffer(&minor, &output);
                                603                 :              0 :             return -1;
                                604                 :                :         }
 1838 sfrost@snowman.net        605         [ +  - ]:CBC         232 :         else if (!(major & GSS_S_CONTINUE_NEEDED))
                                606                 :                :         {
                                607                 :                :             /*
                                608                 :                :              * rfc2744 technically permits context negotiation to be complete
                                609                 :                :              * both with and without a packet to be sent.
                                610                 :                :              */
                                611                 :            232 :             complete_next = true;
                                612                 :                :         }
                                613                 :                : 
  367                           614         [ +  + ]:            232 :         if (delegated_creds != GSS_C_NO_CREDENTIAL)
                                615                 :                :         {
                                616                 :             10 :             pg_store_delegated_credential(delegated_creds);
                                617                 :             10 :             port->gss->delegated_creds = true;
                                618                 :                :         }
                                619                 :                : 
                                620                 :                :         /* Done handling the incoming packet, reset our buffer */
 1838                           621                 :            232 :         PqGSSRecvLength = 0;
                                622                 :                : 
                                623                 :                :         /*
                                624                 :                :          * Check if we have data to send and, if we do, make sure to send it
                                625                 :                :          * all
                                626                 :                :          */
 1555 tgl@sss.pgh.pa.us         627         [ +  - ]:            232 :         if (output.length > 0)
                                628                 :                :         {
 1277 michael@paquier.xyz       629                 :            232 :             uint32      netlen = pg_hton32(output.length);
                                630                 :                : 
 1838 sfrost@snowman.net        631         [ -  + ]:            232 :             if (output.length > PQ_GSS_SEND_BUFFER_SIZE - sizeof(uint32))
                                632                 :                :             {
 1203 tgl@sss.pgh.pa.us         633         [ #  # ]:UBC           0 :                 ereport(COMMERROR,
                                634                 :                :                         (errmsg("server tried to send oversize GSSAPI packet (%zu > %zu)",
                                635                 :                :                                 (size_t) output.length,
                                636                 :                :                                 PQ_GSS_SEND_BUFFER_SIZE - sizeof(uint32))));
                                637                 :              0 :                 gss_release_buffer(&minor, &output);
                                638                 :              0 :                 return -1;
                                639                 :                :             }
                                640                 :                : 
 1838 sfrost@snowman.net        641                 :CBC         232 :             memcpy(PqGSSSendBuffer, (char *) &netlen, sizeof(uint32));
 1555 tgl@sss.pgh.pa.us         642                 :            232 :             PqGSSSendLength += sizeof(uint32);
                                643                 :                : 
                                644                 :            232 :             memcpy(PqGSSSendBuffer + PqGSSSendLength, output.value, output.length);
                                645                 :            232 :             PqGSSSendLength += output.length;
                                646                 :                : 
                                647                 :                :             /* we don't bother with PqGSSSendConsumed here */
                                648                 :                : 
                                649         [ +  + ]:            464 :             while (PqGSSSendNext < PqGSSSendLength)
                                650                 :                :             {
                                651                 :            232 :                 ret = secure_raw_write(port, PqGSSSendBuffer + PqGSSSendNext,
                                652                 :            232 :                                        PqGSSSendLength - PqGSSSendNext);
                                653                 :                : 
                                654                 :                :                 /*
                                655                 :                :                  * If we got back an error and it wasn't just
                                656                 :                :                  * EWOULDBLOCK/EAGAIN/EINTR, then give up.
                                657                 :                :                  */
                                658         [ -  + ]:            232 :                 if (ret < 0 &&
 1555 tgl@sss.pgh.pa.us         659   [ #  #  #  #  :UBC           0 :                     !(errno == EWOULDBLOCK || errno == EAGAIN || errno == EINTR))
                                              #  # ]
                                660                 :                :                 {
 1440                           661                 :              0 :                     gss_release_buffer(&minor, &output);
 1555                           662                 :              0 :                     return -1;
                                663                 :                :                 }
                                664                 :                : 
                                665                 :                :                 /* Wait and retry if we couldn't write yet */
 1838 sfrost@snowman.net        666         [ -  + ]:CBC         232 :                 if (ret <= 0)
                                667                 :                :                 {
 1838 sfrost@snowman.net        668                 :UBC           0 :                     WaitLatchOrSocket(MyLatch,
                                669                 :                :                                       WL_SOCKET_WRITEABLE | WL_EXIT_ON_PM_DEATH,
                                670                 :                :                                       port->sock, 0, WAIT_EVENT_GSS_OPEN_SERVER);
                                671                 :              0 :                     continue;
                                672                 :                :                 }
                                673                 :                : 
 1555 tgl@sss.pgh.pa.us         674                 :CBC         232 :                 PqGSSSendNext += ret;
                                675                 :                :             }
                                676                 :                : 
                                677                 :                :             /* Done sending the packet, reset our buffer */
                                678                 :            232 :             PqGSSSendLength = PqGSSSendNext = 0;
                                679                 :                : 
 1838 sfrost@snowman.net        680                 :            232 :             gss_release_buffer(&minor, &output);
                                681                 :                :         }
                                682                 :                : 
                                683                 :                :         /*
                                684                 :                :          * If we got back that the connection is finished being set up, now
                                685                 :                :          * that we've sent the last packet, exit our loop.
                                686                 :                :          */
                                687         [ +  - ]:            232 :         if (complete_next)
                                688                 :            232 :             break;
                                689                 :                :     }
                                690                 :                : 
                                691                 :                :     /*
                                692                 :                :      * Determine the max packet size which will fit in our buffer, after
                                693                 :                :      * accounting for the length.  be_gssapi_write will need this.
                                694                 :                :      */
                                695                 :            232 :     major = gss_wrap_size_limit(&minor, port->gss->ctx, 1, GSS_C_QOP_DEFAULT,
                                696                 :                :                                 PQ_GSS_SEND_BUFFER_SIZE - sizeof(uint32),
                                697                 :                :                                 &PqGSSMaxPktSize);
                                698                 :                : 
                                699         [ -  + ]:            232 :     if (GSS_ERROR(major))
                                700                 :                :     {
 1203 tgl@sss.pgh.pa.us         701                 :UBC           0 :         pg_GSS_error(_("GSSAPI size check error"), major, minor);
                                702                 :              0 :         return -1;
                                703                 :                :     }
                                704                 :                : 
 1838 sfrost@snowman.net        705                 :CBC         232 :     port->gss->enc = true;
                                706                 :                : 
                                707                 :            232 :     return 0;
                                708                 :                : }
                                709                 :                : 
                                710                 :                : /*
                                711                 :                :  * Return if GSSAPI authentication was used on this connection.
                                712                 :                :  */
                                713                 :                : bool
                                714                 :            320 : be_gssapi_get_auth(Port *port)
                                715                 :                : {
                                716   [ +  -  -  + ]:            320 :     if (!port || !port->gss)
 1838 sfrost@snowman.net        717                 :UBC           0 :         return false;
                                718                 :                : 
 1838 sfrost@snowman.net        719                 :CBC         320 :     return port->gss->auth;
                                720                 :                : }
                                721                 :                : 
                                722                 :                : /*
                                723                 :                :  * Return if GSSAPI encryption is enabled and being used on this connection.
                                724                 :                :  */
                                725                 :                : bool
                                726                 :            320 : be_gssapi_get_enc(Port *port)
                                727                 :                : {
                                728   [ +  -  -  + ]:            320 :     if (!port || !port->gss)
 1838 sfrost@snowman.net        729                 :UBC           0 :         return false;
                                730                 :                : 
 1838 sfrost@snowman.net        731                 :CBC         320 :     return port->gss->enc;
                                732                 :                : }
                                733                 :                : 
                                734                 :                : /*
                                735                 :                :  * Return the GSSAPI principal used for authentication on this connection
                                736                 :                :  * (NULL if we did not perform GSSAPI authentication).
                                737                 :                :  */
                                738                 :                : const char *
                                739                 :            320 : be_gssapi_get_princ(Port *port)
                                740                 :                : {
 1203 tgl@sss.pgh.pa.us         741   [ +  -  -  + ]:            320 :     if (!port || !port->gss)
 1838 sfrost@snowman.net        742                 :UBC           0 :         return NULL;
                                743                 :                : 
 1838 sfrost@snowman.net        744                 :CBC         320 :     return port->gss->princ;
                                745                 :                : }
                                746                 :                : 
                                747                 :                : /*
                                748                 :                :  * Return if GSSAPI delegated credentials were included on this
                                749                 :                :  * connection.
                                750                 :                :  */
                                751                 :                : bool
  330 bruce@momjian.us          752                 :            340 : be_gssapi_get_delegation(Port *port)
                                753                 :                : {
  367 sfrost@snowman.net        754   [ +  -  +  + ]:            340 :     if (!port || !port->gss)
  366 tgl@sss.pgh.pa.us         755                 :              7 :         return false;
                                756                 :                : 
  367 sfrost@snowman.net        757                 :            333 :     return port->gss->delegated_creds;
                                758                 :                : }
        

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