Hacking the Postgres Wire Protocol
Published on: 2025-04-28 02:33:10
Hacking the Postgres wire protocol
Apr 14th, 2025
Lev Kokotov
PgDog is a network proxy and it can see every byte sent between Postgres and the clients. It understands SQL and can infer where queries should go, without requiring changes to application code.
In this article, we discuss how we handle the Postgres wire protocol and manipulate it to serve queries to multiple databases at the same time.
Protocol basics
Postgres has two ways to send queries over the network:
Simple protocol
Extended protocol
The simple protocol is called like that on purpose: it’s very simple. It has just one message, called Query which contains everything the server needs to execute it:
'Q' | \x00\x00\x00& | SELECT * FROM users WHERE id = 25\0
Postgres messages have a standard format. Each message starts with a single ASCII letter (1 byte), identifying the message type. It’s followed by a 32-bit signed integer, indicating the length of the payload, in bytes, with 4 bytes added for itself. The payl
... Read full article.