Skip to content

fix(buf): guard against malformed backend frame lengths causing panics - #1451

Closed
AdamMagued wants to merge 1 commit into
lib:mainfrom
AdamMagued:fix-issue-1447-malformed-frame-panic
Closed

AdamMagued wants to merge 1 commit into
lib:mainfrom
AdamMagued:fix-issue-1447-malformed-frame-panic

Conversation

@AdamMagued

Copy link
Copy Markdown

Fixes #1447

Problem

When receiving a backend message, conn.recvMessage extracts the 4-byte message length header and calculates n := int(binary.BigEndian.Uint32(x[1:])) - 4. If the incoming frame specifies a length less than 4 (including 0, 1, 2, 3) or a negative value when interpreted as a signed 32-bit integer, n becomes negative.

Because n <= len(cn.scratch) evaluated to true for negative values (e.g., -4 <= 512), the code executed r.b = cn.scratch[:n], triggering a slice bounds out of range panic (panic: runtime error: slice bounds out of range [:-4]). A similar condition occurred when parsing column lengths in rows.Next for DataRow messages where invalid column lengths caused slicing panics or out-of-bounds reads.

Solution

  1. In conn.recvMessage, cast the 4-byte length field to a signed 32-bit integer msgLen := int(int32(binary.BigEndian.Uint32(x[1:]))).
  2. Validate that n >= 0 and that msgLen does not exceed the protocol message limit (1 GB). If invalid, mark the connection with driver.ErrBadConn and return an error indicating loss of synchronization.
  3. In rows.Next, validate the column value length l against 0 and len(rs.rb) before slicing.
  4. Add comprehensive unit tests in buf_test.go and an integration test in conn_test.go verifying that malformed frame lengths (zero, sub-header, negative, and oversized) return descriptive errors and mark the connection as bad without panicking.

@arp242 arp242 closed this Oct 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

malformed backend frame length causes panic

2 participants