From 9ee452d1becd66c08106ae54d5ef99e57a2ada47 Mon Sep 17 00:00:00 2001
From: Tatsuo Ishii <ishii@postgresql.org>
Date: Fri, 26 Jun 2026 14:44:17 +0900
Subject: [PATCH v1] Reject sub-minimum ErrorResponse length in
 read_kind_from_backend.
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

read_kind_from_backend() handles a backend ErrorResponse on the V3
path by reading the 4-byte length field, palloc'ing a buffer sized at
ntohl(len), and immediately memcpy()ing all 4 bytes of the
network-order length back into that buffer. When a backend (malicious,
buggy, or speaking a non-V3 dialect that has slipped past earlier
checks) sends a length below 4 $B!=(B i.e. in {0,1,2,3} $B!=(B the palloc
chunk is smaller than sizeof(len) and the memcpy overruns the heap
allocation. The follow-up `len -= 4` then underflows to a huge
unsigned value, which the subsequent `repalloc(unread_p, sizeof(len) +
len)` may wrap, and pool_read2() is asked for a colossal payload $B!=(B
all on top of an already-corrupted heap.

Reject any ntohl(len) below sizeof(len) up front with ereport(ERROR,
...). The error path is the existing longjmp-based one used by every
other malformed-input check in this function, so the connection is
torn down cleanly without touching unread_p.

Reported-by: Emond Papegaaij <emond.papegaaij@gmail.com>
Reported-by: Claude code
Author: Tatsuo Ishii <ishii@postgresql.org>
Discussion:
Backpatch-through: v4.3
---
 src/protocol/pool_process_query.c | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/src/protocol/pool_process_query.c b/src/protocol/pool_process_query.c
index a2fea2640..202afa2a3 100644
--- a/src/protocol/pool_process_query.c
+++ b/src/protocol/pool_process_query.c
@@ -3569,6 +3569,10 @@ read_kind_from_backend(POOL_CONNECTION *frontend, POOL_CONNECTION_POOL *backend,
 				if (major == PROTO_MAJOR_V3)
 				{
 					pool_read(CONNECTION(backend, i), &len, sizeof(len));
+					if (ntohl(len) < sizeof(len))
+						ereport(ERROR,
+								(errmsg("read_kind_from_backend: ErrorResponse length %u is below the %zu-byte minimum",
+										ntohl(len), sizeof(len))));
 					unread_len = sizeof(len);
 					unread_p = palloc(ntohl(len));
 					memcpy(unread_p, &len, sizeof(len));
-- 
2.43.0

