1From 586b074026d703c29057b04b1318e984701fe195 Mon Sep 17 00:00:00 2001
2From: Changqing Li <changqing.li@windriver.com>
3Date: Thu, 2 Mar 2023 19:10:47 +0800
4Subject: [PATCH] Properly NULL-terminate GSS receive buffer on error packet
5 reception
6
7pqsecure_open_gss() includes a code path handling error messages with
8v2-style protocol messages coming from the server.  The client-side
9buffer holding the error message does not force a NULL-termination, with
10the data of the server getting copied to the errorMessage of the
11connection.  Hence, it would be possible for a server to send an
12unterminated string and copy arbitrary bytes in the buffer receiving the
13error message in the client, opening the door to a crash or even data
14exposure.
15
16As at this stage of the authentication process the exchange has not been
17completed yet, this could be abused by an attacker without Kerberos
18credentials.  Clients that have a valid kerberos cache are vulnerable as
19libpq opportunistically requests for it except if gssencmode is
20disabled.
21
22Author: Jacob Champion
23Backpatch-through: 12
24Security: CVE-2022-41862
25
26Upstream-Status: Backport [https://github.com/postgres/postgres/commit/71c37797d7bd78266146a5829ab62b3687c47295]
27CVE: CVE-2022-41862
28
29Signed-off-by: Changqing Li <changqing.li@windriver.com>
30---
31 src/interfaces/libpq/fe-secure-gssapi.c | 3 ++-
32 1 file changed, 2 insertions(+), 1 deletion(-)
33
34diff --git a/src/interfaces/libpq/fe-secure-gssapi.c b/src/interfaces/libpq/fe-secure-gssapi.c
35index c783a53..a42ebc0 100644
36--- a/src/interfaces/libpq/fe-secure-gssapi.c
37+++ b/src/interfaces/libpq/fe-secure-gssapi.c
38@@ -577,7 +577,8 @@ pqsecure_open_gss(PGconn *conn)
39 				return result;
40
41 			PqGSSRecvLength += ret;
42-
43+			Assert(PqGSSRecvLength < PQ_GSS_RECV_BUFFER_SIZE);
44+			PqGSSRecvBuffer[PqGSSRecvLength] = '\0';
45 			appendPQExpBuffer(&conn->errorMessage, "%s\n", PqGSSRecvBuffer + 1);
46
47 			return PGRES_POLLING_FAILED;
48--
492.25.1
50
51