1/*-------------------------------------------------------------------------
4 * The front-end (client) encryption support for GSSAPI
6 * Portions Copyright (c) 2016-2025, PostgreSQL Global Development Group
9 * src/interfaces/libpq/fe-secure-gssapi.c
11 *-------------------------------------------------------------------------
23 * Require encryption support, as well as mutual authentication and
24 * tamperproofing measures.
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
30 * Handle the encryption/decryption of data using GSSAPI.
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.
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).
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.
50 * Therefore, this #define is effectively part of the protocol
51 * spec and can't ever be changed.
53 #define PQ_GSS_MAX_PACKET_SIZE 16384 /* includes uint32 header word */
56 * However, during the authentication exchange we must cope with whatever
57 * message size the GSSAPI library wants to send (because our protocol
58 * doesn't support splitting those messages). Depending on configuration
59 * those messages might be as much as 64kB.
61 #define PQ_GSS_AUTH_BUFFER_SIZE 65536 /* includes uint32 header word */
64 * We need these state variables per-connection. To allow the functions
65 * in this file to look mostly like those in be-secure-gssapi.c, set up
68 #define PqGSSSendBuffer (conn->gss_SendBuffer)
69 #define PqGSSSendLength (conn->gss_SendLength)
70 #define PqGSSSendNext (conn->gss_SendNext)
71 #define PqGSSSendConsumed (conn->gss_SendConsumed)
72 #define PqGSSRecvBuffer (conn->gss_RecvBuffer)
73 #define PqGSSRecvLength (conn->gss_RecvLength)
74 #define PqGSSResultBuffer (conn->gss_ResultBuffer)
75 #define PqGSSResultLength (conn->gss_ResultLength)
76 #define PqGSSResultNext (conn->gss_ResultNext)
77 #define PqGSSMaxPktSize (conn->gss_MaxPktSize)
81 * Attempt to write len bytes of data from ptr to a GSSAPI-encrypted connection.
83 * The connection must be already set up for GSSAPI encryption (i.e., GSSAPI
84 * transport negotiation is complete).
86 * On success, returns the number of data bytes consumed (possibly less than
87 * len). On failure, returns -1 with errno set appropriately. If the errno
88 * indicates a non-retryable error, a message is added to conn->errorMessage.
89 * For retryable errors, caller should call again (passing the same or more
90 * data) once the socket is ready.
97 gss_buffer_desc
input,
98 output = GSS_C_EMPTY_BUFFER;
100 size_t bytes_to_encrypt;
101 size_t bytes_encrypted;
102 gss_ctx_id_t gctx =
conn->gctx;
105 * When we get a retryable failure, we must not tell the caller we have
106 * successfully transmitted everything, else it won't retry. For
107 * simplicity, we claim we haven't transmitted anything until we have
108 * successfully transmitted all "len" bytes. Between calls, the amount of
109 * the current input data that's already been encrypted and placed into
110 * PqGSSSendBuffer (and perhaps transmitted) is remembered in
111 * PqGSSSendConsumed. On a retry, the caller *must* be sending that data
112 * again, so if it offers a len less than that, something is wrong.
114 * Note: it may seem attractive to report partial write completion once
115 * we've successfully sent any encrypted packets. However, doing that
116 * expands the state space of this processing and has been responsible for
117 * bugs in the past (cf. commit d053a879b). We won't save much,
118 * typically, by letting callers discard data early, so don't risk it.
123 "GSSAPI caller failed to retransmit all data needing to be retried\n");
128 /* Discount whatever source data we already encrypted. */
133 * Loop through encrypting data and sending it out until it's all done or
134 * pqsecure_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).
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
159 * Check if this was a partial write, and if so, move forward that
160 * far in our buffer and try again.
168 /* We've successfully sent whatever data was in the buffer. */
173 * Check if there are any bytes left to encrypt. If not, we're done.
175 if (!bytes_to_encrypt)
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.
186 input.length = bytes_to_encrypt;
188 input.value = (
char *) ptr + bytes_encrypted;
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.
197 major = gss_wrap(&minor, gctx, 1, GSS_C_QOP_DEFAULT,
199 if (major != GSS_S_COMPLETE)
222 bytes_encrypted +=
input.length;
223 bytes_to_encrypt -=
input.length;
226 /* 4 network-order bytes of length, then payload */
234 /* Release buffer storage allocated by GSSAPI */
235 gss_release_buffer(&minor, &
output);
238 /* If we get here, our counters should all match up. */
242 /* We're reporting all the data as sent, so reset PqGSSSendConsumed. */
245 ret = bytes_encrypted;
248 /* Release GSSAPI buffer storage, if we didn't already */
250 gss_release_buffer(&minor, &
output);
255 * Read up to len bytes of data into ptr from a GSSAPI-encrypted connection.
257 * The connection must be already set up for GSSAPI encryption (i.e., GSSAPI
258 * transport negotiation is complete).
260 * Returns the number of data bytes read, or on failure, returns -1
261 * with errno set appropriately. If the errno indicates a non-retryable
262 * error, a message is added to conn->errorMessage. For retryable errors,
263 * caller should call again once the socket is ready.
270 gss_buffer_desc
input = GSS_C_EMPTY_BUFFER,
271 output = GSS_C_EMPTY_BUFFER;
273 size_t bytes_returned = 0;
274 gss_ctx_id_t gctx =
conn->gctx;
277 * The plan here is to read one incoming encrypted packet into
278 * PqGSSRecvBuffer, decrypt it into PqGSSResultBuffer, and then dole out
279 * data from there to the caller. When we exhaust the current input
280 * packet, read another.
282 while (bytes_returned <
len)
286 /* Check if we have data in our buffer that we can return immediately */
290 size_t bytes_to_copy =
Min(bytes_in_buffer,
len - bytes_returned);
293 * Copy the data from our result buffer into the caller's buffer,
294 * at the point where we last left off filling their buffer.
298 bytes_returned += bytes_to_copy;
301 * At this point, we've either filled the caller's buffer or
302 * emptied our result buffer. Either way, return to caller. In
303 * the second case, we could try to read another encrypted packet,
304 * but the odds are good that there isn't one available. (If this
305 * isn't true, we chose too small a max packet size.) In any
306 * case, there's no harm letting the caller process the data we've
312 /* Result buffer is empty, so reset buffer pointers */
316 * Because we chose above to return immediately as soon as we emit
317 * some data, bytes_returned must be zero at this point. Therefore
318 * the failure exits below can just return -1 without worrying about
319 * whether we already emitted some data.
321 Assert(bytes_returned == 0);
324 * At this point, our result buffer is empty with more bytes being
325 * requested to be read. We are now ready to load the next packet and
326 * decrypt it (entirely) into our result buffer.
329 /* Collect the length if we haven't already */
335 /* If ret <= 0, pqsecure_raw_read already set the correct errno */
341 /* If we still haven't got the length, return to the caller */
349 /* Decode the packet length and check for overlength packet */
355 (
size_t)
input.length,
362 * Read as much of the packet as we are able to on this call into
363 * wherever we left off from the last time we were called.
367 /* If ret <= 0, pqsecure_raw_read already set the correct errno */
373 /* If we don't yet have the whole packet, return to the caller */
381 * We now have the full packet and we can perform the decryption and
382 * refill our result buffer, then loop back up to pass data back to
383 * the caller. Note that error exits below here must take care of
384 * releasing the gss output buffer.
390 major = gss_unwrap(&minor, gctx, &
input, &
output, &conf_state, NULL);
391 if (major != GSS_S_COMPLETE)
411 /* Our receive buffer is now empty, reset it */
414 /* Release buffer storage allocated by GSSAPI */
415 gss_release_buffer(&minor, &
output);
418 ret = bytes_returned;
421 /* Release GSSAPI buffer storage, if we didn't already */
423 gss_release_buffer(&minor, &
output);
428 * Simple wrapper for reading from pqsecure_raw_read.
430 * This takes the same arguments as pqsecure_raw_read, plus an output parameter
431 * to return the number of bytes read. This handles if blocking would occur and
432 * if we detect EOF on the connection.
475 * Negotiate GSSAPI transport for a connection. When complete, returns
476 * PGRES_POLLING_OK. Will return PGRES_POLLING_READING or
477 * PGRES_POLLING_WRITING as appropriate whenever it would block, and
478 * PGRES_POLLING_FAILED if transport could not be negotiated.
489 gss_buffer_desc
input = GSS_C_EMPTY_BUFFER,
490 output = GSS_C_EMPTY_BUFFER;
493 * If first time through for this connection, allocate buffers and
494 * initialize state variables. By malloc'ing the buffers separately, we
495 * ensure that they are sufficiently aligned for the length-word accesses
496 * that we do in some places in this file.
498 * We'll use PQ_GSS_AUTH_BUFFER_SIZE-sized buffers until transport
499 * negotiation is complete, then switch to PQ_GSS_MAX_PACKET_SIZE.
516 * Check if we have anything to send from a prior call and if so, send it.
542 * Client sends first, and sending creates a context, therefore this will
543 * be false the first time through, and then when we get called again we
544 * will check for incoming data.
548 /* Process any incoming data we might have */
550 /* See if we are still trying to get the length */
553 /* Attempt to get the length first */
565 * Check if we got an error packet
567 * This is safe to do because we shouldn't ever get a packet over 8192
568 * and therefore the actual length bytes, being that they are in
569 * network byte order, for any real packet will start with two zero
575 * For an error packet during startup, we don't get a length, so
576 * simply read as much as we can fit into our buffer (as a string,
577 * so leave a spot at the end for a NULL byte too) and report that
578 * back to the caller.
594 * We should have the whole length at this point, so pull it out and
595 * then read whatever we have left of the packet
598 /* Get the length and check for over-length packet */
603 (
size_t)
input.length,
609 * Read as much of the packet as we are able to on this call into
610 * wherever we left off from the last time we were called.
620 * If we got less than the rest of the packet then we need to return
621 * and be called again.
629 /* Load the service name (no-op if already done */
636 /* Acquire credentials if possible */
637 if (
conn->gcred == GSS_C_NO_CREDENTIAL)
641 * We have credentials and gssdelegation is enabled, so request
642 * credential delegation. This may or may not actually result in
643 * credentials being delegated- it depends on if the forwardable flag
644 * has been set in the credential and if the server is configured to
645 * accept delegated credentials.
647 if (
conn->gcred != GSS_C_NO_CREDENTIAL)
648 gss_flags |= GSS_C_DELEG_FLAG;
652 * Call GSS init context, either with an empty input, or with a complete
653 * packet from the server.
655 major = gss_init_sec_context(&minor,
conn->gcred, &
conn->gctx,
656 conn->gtarg_nam, GSS_C_NO_OID,
657 gss_flags, 0, 0, &
input, NULL,
660 /* GSS Init Sec Context uses the whole packet, so clear it */
663 if (GSS_ERROR(major))
673 * We're done - hooray! Set flag to tell the low-level I/O routines
674 * to do GSS wrapping/unwrapping.
680 gss_release_cred(&minor, &
conn->gcred);
681 conn->gcred = GSS_C_NO_CREDENTIAL;
682 gss_release_buffer(&minor, &
output);
685 * Release the large authentication buffers and allocate the ones we
686 * want for normal operation. (This maneuver is safe only because
687 * pqDropConnection will drop the buffers; otherwise, during a
688 * reconnection we'd be at risk of using undersized buffers during
706 * Determine the max packet size which will fit in our buffer, after
707 * accounting for the length. pg_GSS_write will need this.
709 major = gss_wrap_size_limit(&minor,
conn->gctx, 1, GSS_C_QOP_DEFAULT,
713 if (GSS_ERROR(major))
723 /* Must have output.length > 0 */
729 gss_release_buffer(&minor, &
output);
733 /* Queue the token for writing */
742 /* We don't bother with PqGSSSendConsumed here */
744 /* Release buffer storage allocated by GSSAPI */
745 gss_release_buffer(&minor, &
output);
747 /* Ask to be called again to write data */
752 * GSSAPI Information functions.
756 * Return the GSSAPI Context itself.
768 * Return true if GSSAPI encryption is in use.
void pg_GSS_error(const char *errmsg, OM_uint32 maj_stat, OM_uint32 min_stat)
static void cleanup(void)
int pg_GSS_load_servicename(PGconn *conn)
bool pg_GSS_have_cred_cache(gss_cred_id_t *cred_out)
int pqReadReady(PGconn *conn)
#define PqGSSResultLength
#define PQ_GSS_AUTH_BUFFER_SIZE
ssize_t pg_GSS_read(PGconn *conn, void *ptr, size_t len)
ssize_t pg_GSS_write(PGconn *conn, const void *ptr, size_t len)
void * PQgetgssctx(PGconn *conn)
#define PqGSSSendConsumed
int PQgssEncInUse(PGconn *conn)
#define GSS_REQUIRED_FLAGS
PostgresPollingStatusType pqsecure_open_gss(PGconn *conn)
static PostgresPollingStatusType gss_read(PGconn *conn, void *recv_buffer, size_t length, ssize_t *ret)
#define PQ_GSS_MAX_PACKET_SIZE
#define PqGSSResultBuffer
ssize_t pqsecure_raw_read(PGconn *conn, void *ptr, size_t len)
ssize_t pqsecure_raw_write(PGconn *conn, const void *ptr, size_t len)
Assert(PointerIsAligned(start, uint64))
PostgresPollingStatusType
#define SOCK_ERRNO_SET(e)
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
PQExpBufferData errorMessage