Skip to content

libpq/psql: prevent named-bind escape buffer overruns - #1568

Closed
yyqdbngt wants to merge 3 commits into
IvorySQL:masterfrom
yyqdbngt:wangyue/fix-1554-named-bind-escape
Closed

yyqdbngt wants to merge 3 commits into
IvorySQL:masterfrom
yyqdbngt:wangyue/fix-1554-named-bind-escape

Conversation

@yyqdbngt

@yyqdbngt yyqdbngt commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • centralize construction of the libpq named-bind parameter-description query
  • reserve space for worst-case quote doubling and the terminating NUL
  • reject libpq size overflow and handle empty queries safely
  • fix the matching quote-doubling allocation in psql's get_hostvariables()

Root cause

The two libpq named-bind execution paths and psql's host-variable scanner allocated only 2 * query_length bytes for escaped SQL text. An all-quote input can fill that allocation before the terminating NUL. The libpq path also needed an explicit overflow check and safe handling of empty input.

Verification

  • targeted compilation of src/interfaces/libpq/ivy-exec.c
  • targeted compilation of src/bin/psql/common.c
  • empty, quoted, and all-quote libpq boundary cases under AddressSanitizer

Fixes #1554.

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of SQL parameter descriptions containing quote characters.
    • Added safeguards against oversized SQL input and allocation failures.
    • Prevented potential buffer overflows when processing host variables.
    • Improved error reporting for inputs that exceed supported size limits.

@coderabbitai

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds a shared helper for safely constructing parameter-description queries. Both named-bind replacement paths use it. get_hostvariables now validates doubled-length allocations and reserves space for the terminating NUL byte.

Changes

Parameter-description query safety

Layer / File(s) Summary
Shared query builder and replacement-path integration
src/interfaces/libpq/ivy-exec.c
IvyBuildParameterDescriptionQuery centralizes quote escaping, overflow checks, terminator space, and allocation-failure handling. Both named-bind replacement paths use the helper.
psql host-variable buffer sizing
src/bin/psql/common.c
get_hostvariables rejects overflowing lengths and allocates space for doubled quotes plus the terminating NUL byte.

Estimated code review effort: 2 (Simple) | ~10 minutes

Mergeability Score: 🔵 Low · up to e4b52

The change prevents named-bind buffer overruns, but psql can leak a small query buffer when host-variable validation rejects NULL or oversized input. The PR is mergeable with explicit owner awareness or a follow-up to release that buffer on validation failures.

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: preventing buffer overruns during named-bind SQL escaping.
Linked Issues check ✅ Passed The changes address issue #1554 by fixing quote-doubling allocation, overflow handling, empty-query safety, and both libpq paths.
Out of Scope Changes check ✅ Passed The psql allocation fix is related to the same named-bind quote-doubling vulnerability and supports the stated pull request objectives.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@jiaoshuntian

Copy link
Copy Markdown
Collaborator

It looks like they are doing the same thing. #1569

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/bin/psql/common.c`:
- Line 3646: In the surrounding SQL quoting function, compute the input length
once and validate it against (SIZE_MAX - 1) / 2 before calculating the
allocation size. Reject oversized input through the function’s existing error
path, then call pg_malloc0() with the safely computed doubled length plus
terminator so the subsequent copy remains within bounds.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 85675e9f-7d08-4b3d-b737-80764a64686f

📥 Commits

Reviewing files that changed from the base of the PR and between 8051088 and 561846c.

📒 Files selected for processing (1)
  • src/bin/psql/common.c

Comment thread src/bin/psql/common.c Resolved
@yyqdbngt yyqdbngt changed the title libpq: prevent named-bind escape buffer overrun libpq/psql: prevent named-bind escape buffer overruns Aug 12, 2026
get_hostvariables doubled the query length plus a NUL byte before calling pg_malloc0(). A wrapped size could slip through and the copy loop would then write past the allocated buffer. Reject inputs larger than (SIZE_MAX - 1) / 2 up front, matching the overflow guard already used in IvyBuildParameterDescriptionQuery.

Assisted-by: opencode:qwen/qwen3.8-max-preview
Signed-off-by: yyqdbngt <[email protected]>
@yyqdbngt

Copy link
Copy Markdown
Contributor Author

@jiaoshuntian Thanks for the heads-up. #1569 was closed without merging, and its author also left it as is ("so let they do, it's fine"), so this PR remains the active fix for #1554. It covers both named-bind replacement paths in libpq via the shared IvyBuildParameterDescriptionQuery helper and the matching psql host-variable escape buffer, including the overflow guard now added in e4b5239. Please let me know if you'd like any part of #1569 folded in.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/bin/psql/common.c`:
- Around line 3643-3656: Release the PQExpBuffer allocated by createPQExpBuffer
before both early returns in the surrounding escape-query function: the sql ==
NULL validation path and the sql_len overflow path. Prefer moving
createPQExpBuffer below these checks when safe; otherwise call
destroyPQExpBuffer(query) before each return while preserving existing error
handling.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: fd519a7d-1197-419c-9eef-d420eed7c02d

📥 Commits

Reviewing files that changed from the base of the PR and between 561846c and e4b5239.

📒 Files selected for processing (1)
  • src/bin/psql/common.c

Comment thread src/bin/psql/common.c
Comment on lines 3643 to +3656
if (!sql)
return NULL;

/*
* Each input byte may be emitted twice (quoted quotes) plus one NUL
* terminator, so reject inputs whose doubled length would overflow
* before pg_malloc0() sees a wrapped size.
*/
sql_len = strlen(sql);
if (sql_len > (SIZE_MAX - 1) / 2)
{
pg_log_error("query is too long to escape for host-variable binding");
*error = true;
return NULL;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Release query on validation failures.

query is allocated at Line 3635 before these checks. The sql == NULL return at Lines 3643-3644 and the overflow return at Lines 3653-3656 bypass destroyPQExpBuffer(query). Move createPQExpBuffer() below both checks, or destroy query before each return.

Proposed fix
-PQExpBuffer query = createPQExpBuffer();
+PQExpBuffer query;
...
 if (sql_len > (SIZE_MAX - 1) / 2)
 {
 	pg_log_error("query is too long to escape for host-variable binding");
 	*error = true;
 	return NULL;
 }
 
+query = createPQExpBuffer();
 newsql = pg_malloc0(sql_len * 2 + 1);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (!sql)
return NULL;
/*
* Each input byte may be emitted twice (quoted quotes) plus one NUL
* terminator, so reject inputs whose doubled length would overflow
* before pg_malloc0() sees a wrapped size.
*/
sql_len = strlen(sql);
if (sql_len > (SIZE_MAX - 1) / 2)
{
pg_log_error("query is too long to escape for host-variable binding");
*error = true;
return NULL;
PQExpBuffer query;
if (!sql)
return NULL;
/*
* Each input byte may be emitted twice (quoted quotes) plus one NUL
* terminator, so reject inputs whose doubled length would overflow
* before pg_malloc0() sees a wrapped size.
*/
sql_len = strlen(sql);
if (sql_len > (SIZE_MAX - 1) / 2)
{
pg_log_error("query is too long to escape for host-variable binding");
*error = true;
return NULL;
}
query = createPQExpBuffer();
newsql = pg_malloc0(sql_len * 2 + 1);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/bin/psql/common.c` around lines 3643 - 3656, Release the PQExpBuffer
allocated by createPQExpBuffer before both early returns in the surrounding
escape-query function: the sql == NULL validation path and the sql_len overflow
path. Prefer moving createPQExpBuffer below these checks when safe; otherwise
call destroyPQExpBuffer(query) before each return while preserving existing
error handling.

@jiaoshuntian jiaoshuntian self-assigned this Aug 20, 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.

Named-bind query escaping can overrun its heap buffer

2 participants