PostgreSQL码农集散地

PostgreSQL 18 preview - 连接协议改进, cancel key增加到256字节

PostgreSQL 18 preview - 连接协议改进, cancel key增加到256字节

要cancel PostgreSQL的某个会话正在执行的SQL, 实际上不需要连到数据库里面, 如果你知道会话的PID, 可以直接通过socket向postmaster监听发起相关数据包即可, 需要包含pid和cancel key.

cancel key是建立会话时随机生成的一个32位数字.

所以可以无限尝试, 最终cancel一个已知PID的长连接的会话.

攻击方法参考下文 :

  • 《PostgreSQL cancel 通信协议、信号和代码》
  • 《PostgreSQL cancel 安全漏洞》

PostgreSQL 18 增强了连接协议3.2, 采用了最高256字节的cancel key, 使得连接池的软件商可以自定义这个cancel key, 放更多的信息进去, 实现更灵活的功能.

https://git.postgresql.org/gitweb/?p=postgresql.git;a=commit;h=a460251f0a1ac987f0225203ff9593704da0b1a9

Make cancel request keys longer  

author Heikki Linnakangas <[email protected]>   
Wed, 2 Apr 2025 13:41:48 +0000 (16:41 +0300)  
committer Heikki Linnakangas <[email protected]>   
Wed, 2 Apr 2025 13:41:48 +0000 (16:41 +0300)  
commit a460251f0a1ac987f0225203ff9593704da0b1a9  
tree 009893fb5dc0e934b15abf6eabfe20fda63b3d4d tree  
parent 285613c60a7aff5daaf281c67002483b0d26e715 commit | diff  
Make cancel request keys longer  

Currently, the cancel request key is a 32-bit token, which isn't very  
much entropy. If you want to cancel another session'
s query, you can  
brute-force it. In most environments, an unauthorized cancellation of  
a query isn't very serious, but it nevertheless would be nice to have  
more protection from it. Hence make the key longer, to make it harder  
to guess.  

The longer cancellation keys are generated when using the new protocol  
version 3.2. For connections using version 3.0, short 4-bytes keys are  
still used.  

The new longer key length is not hardcoded in the protocol anymore,  
the client is expected to deal with variable length keys, up to 256  
bytes. This flexibility allows e.g. a connection pooler to add more  
information to the cancel key, which might be useful for finding the  
connection.  

Reviewed-by: Jelte Fennema-Nio <[email protected]>  
Reviewed-by: Robert Haas <[email protected]> (earlier versions)  
Discussion: https://www.postgresql.org/message-id/[email protected]