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