Skip to content

Fix heap buffer overrun in named-bind query escaping - #1569

Merged
gaoxueyu merged 2 commits into
IvorySQL:masterfrom
Aias00:fix/ivy-query-escape-overflow-1554
Aug 14, 2026
Merged

gaoxueyu merged 2 commits into
IvorySQL:masterfrom
Aias00:fix/ivy-query-escape-overflow-1554

Conversation

@Aias00

@Aias00 Aias00 commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #1554: the escaped-query buffer in the named-bind path was allocated as 2 * query_length bytes. When the input query consists entirely of single quotes, the escaping loop writes exactly 2 * query_length bytes and the terminating NUL is then written one byte past the heap allocation.

Four sites share the same manual escaping pattern and get the same fix:

  • Ivyreplacenamebindtoposition() in src/interfaces/libpq/ivy-exec.c — allocate 2 * len + 1, compute with size_t arithmetic, check malloc() failure (previously unchecked, would crash on OOM).
  • Ivyreplacenamebindtoposition2() in src/interfaces/libpq/ivy-exec.c — same fix; the +1 also makes empty input produce a valid one-byte empty string buffer instead of a NUL write through a zero-length malloc(0).
  • get_hostvariables() in src/bin/psql/common.c — same buffer overrun confirmed; allocate 2 * len + 1 (empty input was already safe here because pg_malloc0(0) maps to a 1-byte allocation).
  • psqlplus VARIABLE missing-termination-quote handling in src/bin/psql/mainloop.c — same overrun: a quote-only init_value fills the 2 * len buffer and the terminating NUL lands one byte past; allocate 2 * len + 1.

Reviewed other quote-doubling sites for the same pattern: pg_upgrade/util.c, psql/command.c and tab-complete.in.c already size with +2/+3; fe_utils/string_utils.c uses a growing PQExpBuffer; fe-connect.c and tsearchcmds.c are parsers, not escaping copies.

Test plan

  • make -C src/interfaces/libpq ivy-exec.o, make -C src/bin/psql common.o and make -C src/bin/psql mainloop.o compile cleanly with the changes.
  • Full libpq link is currently blocked on this machine by a pre-existing, unrelated ivy_sema.c build error on macOS (separate branch fix-ivy-sema-include-guards); the changed translation units themselves compile cleanly.
  • Recommend an AddressSanitizer run of the affected paths (prepare a query whose bytes are all single quotes, e.g. '') to confirm the overrun is gone.

Summary by CodeRabbit

  • Bug Fixes
    • Fixed SQL text handling to ensure duplicated quotes are safely terminated.
    • Improved query parameter escaping to prevent truncated or malformed queries.
    • Added graceful handling for memory-allocation failures during query processing.

The escaped-query buffer was allocated as 2 * query length, which is
exactly consumed when the input consists entirely of single quotes;
the terminating NUL was then written one byte past the heap allocation
in Ivyreplacenamebindtoposition(), Ivyreplacenamebindtoposition2()
and get_hostvariables(). Allocate an extra byte for the NUL, compute
the size with size_t arithmetic to avoid overflow, and check malloc()
failure in the libpq paths.

Closes IvorySQL#1554
@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The changes fix buffer sizing for escaped quotes and terminating NUL bytes. Named-bind replacement helpers now clean up and report errors when allocation fails.

Changes

Query buffer safety

Layer / File(s) Summary
Escaped query allocation and failure handling
src/interfaces/libpq/ivy-exec.c, src/bin/psql/common.c, src/bin/psql/mainloop.c
Named-bind replacement helpers reserve space for the terminating NUL byte and handle allocation failure. SQL quote duplication and missing-quote diagnostics also reserve terminator space.

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

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Linked Issues check ❓ Inconclusive The changes address NUL space, empty input, and allocation failures, but the summary does not confirm explicit overflow rejection required by [#1554]. Confirm that both named-bind paths reject allocation-size overflow before allocation, and add or provide evidence of coverage for this requirement.
✅ Passed checks (4 passed)
Check name Status Explanation
Out of Scope Changes check ✅ Passed The additional fixes in common.c and mainloop.c address the same NUL-termination overrun pattern and remain within the bug-fix scope.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the primary fix for heap buffer overruns in named-bind query escaping.
✨ 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.

The psqlplus VARIABLE command path in mainloop.c doubled quotes into a
2 * length buffer; for input made entirely of quote characters the
terminating NUL was written one byte past the allocation. Allocate an
extra byte.

@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/interfaces/libpq/ivy-exec.c`:
- Around line 3800-3806: In src/interfaces/libpq/ivy-exec.c at lines 3800-3806
and 4094-4101, change IvyPreparedStatement.query_len and the local query_len
variables to size_t, then add checked arithmetic for doubled-quote and wrapper
allocation sizes before allocating or copying, preserving the existing
allocation-error handling. The src/bin/psql/common.c site at line 3646 requires
no direct change because its PQExpBuffer limit bounds the size_t arithmetic.
🪄 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: 60e327ee-a41a-4d83-844b-2e15aa7ca226

📥 Commits

Reviewing files that changed from the base of the PR and between b21cd66 and 4fe229c.

📒 Files selected for processing (2)
  • src/bin/psql/common.c
  • src/interfaces/libpq/ivy-exec.c

Comment on lines +3800 to +3806
newsql = malloc((size_t) stmtHandle->query_len * 2 + 1); /* doubled quotes plus NUL */
if (newsql == NULL)
{
free(query);
snprintf(errmsg, size_error_buf, "%s", "failed to allocate memory");
return 0;
}

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- ivy-exec target contexts ---'
sed -n '3740,3835p' src/interfaces/libpq/ivy-exec.c
sed -n '4035,4125p' src/interfaces/libpq/ivy-exec.c

printf '%s\n' '--- psql target context ---'
sed -n '3595,3675p' src/bin/psql/common.c

printf '%s\n' '--- declarations and related arithmetic ---'
rg -n -C 4 'query_len|newsql|strlen\(sql\) \* 2|pg_malloc0' \
  src/interfaces/libpq/ivy-exec.c src/bin/psql/common.c

printf '%s\n' '--- allocator definitions and overflow helpers ---'
rg -n -C 4 'pg_malloc0|pg_malloc|add_size|mul_size|MaxAllocSize|SIZE_MAX' \
  src/include src/common src/port src/interfaces/libpq src/bin/psql \
  -g '*.[ch]' -g '*.c' -g '*.h' | head -n 500

Repository: IvorySQL/IvorySQL

Length of output: 49641


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- IvyPreparedStatement definition ---'
rg -n -C 12 'IvyPreparedStatement|query_len' \
  src/interfaces/libpq src/include src/bin/psql -g '*.[ch]' -g '*.c' -g '*.h' | head -n 500

printf '%s\n' '--- Ivy statement construction and query-length validation ---'
rg -n -C 8 'IvyStmtPrepare|query_len|strlen\(query\)|strdup\(query\)' \
  src/interfaces/libpq/ivy-exec.c src/interfaces/libpq -g '*.[ch]' -g '*.c' | head -n 700

printf '%s\n' '--- psql allocator declarations and definitions ---'
rg -n -C 12 'pg_malloc0\s*\(|pg_malloc_extended|pg_malloc\s*\(' \
  src/include src/common src/port src/interfaces/libpq src/bin/psql \
  -g '*.[ch]' -g '*.c' -g '*.h' | head -n 700

printf '%s\n' '--- relevant maximum-size definitions ---'
rg -n -C 8 'MaxAllocSize|SIZE_MAX|INT_MAX|PQExpBufferData|createPQExpBuffer' \
  src/include src/common src/interfaces/libpq src/bin/psql \
  -g '*.[ch]' -g '*.c' -g '*.h' | head -n 700

Repository: IvorySQL/IvorySQL

Length of output: 50374


🏁 Script executed:

#!/bin/bash
set -eu

python3 - <<'PY'
import ctypes

sizes = [2**31 - 1, 2**32 - 1, 2**63 - 1, 2**64 - 1]
size_max = 2**64 - 1
for n in sizes:
    print(f"n={n}")
    print(f"  size_t expression (n * 2 + 1) modulo 2^64 = {(n * 2 + 1) & size_max}")
    # The Ivy local int calculation is only meaningful after implementation-defined
    # conversion, so show the mathematical size and the int-range boundary.
    print(f"  mathematical doubled allocation = {n * 2 + 1}")
    print(f"  fits signed int: {-(2**31) <= n * 2 + 1 <= 2**31 - 1}")
PY

Repository: IvorySQL/IvorySQL

Length of output: 782


🏁 Script executed:

#!/bin/bash
set -eu

python3 - <<'PY'
sizes = [2**31 - 1, 2**32 - 1, 2**63 - 1, 2**64 - 1]
size_max = 2**64 - 1

for n in sizes:
    print(f"n={n}")
    print(f"  size_t expression modulo 2^64: {(n * 2 + 1) & size_max}")
    print(f"  mathematical allocation: {n * 2 + 1}")
    print(f"  fits signed int: {-2**31 <= n * 2 + 1 <= 2**31 - 1}")
PY

Repository: IvorySQL/IvorySQL

Length of output: 694


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- frontend allocation functions ---'
rg -n -C 20 'pg_malloc0\s*\(|pg_malloc_extended\s*\(' \
  src/fe_utils src/common src/port src/include \
  -g '*.[ch]' -g '*.c' -g '*.h' | head -n 300

printf '%s\n' '--- size limits and PQExpBuffer implementation ---'
rg -n -C 10 'define MaxAllocSize|MaxAllocSize|PQExpBufferData|appendPQExpBuffer|enlargePQExpBuffer|createPQExpBuffer' \
  src/include src/common src/fe_utils src/bin/psql \
  -g '*.[ch]' -g '*.c' -g '*.h' | head -n 500

printf '%s\n' '--- get_hostvariables callers and SQL buffer sources ---'
rg -n -C 12 'get_hostvariables\s*\(|get_hostvariables' \
  src/bin/psql src/include -g '*.[ch]' -g '*.c' -g '*.h'

printf '%s\n' '--- exact Ivy call paths and query length arguments ---'
rg -n -C 10 'IvyStmtPrepare\s*\(|IvyCreatePreparedStatement\s*\(' \
  src/interfaces src/bin -g '*.[ch]' -g '*.c' -g '*.h' | head -n 500

Repository: IvorySQL/IvorySQL

Length of output: 50373


🏁 Script executed:

#!/bin/bash
set -eu

python3 - <<'PY'
# Compute the first size at which each expression cannot be represented.
# The fixed SQL wrapper is the literal used by both Ivy paths.
wrapper = len("select * from get_parameter_description(") + 5
int_max = 2**31 - 1
size_max = 2**64 - 1

print("wrapper_length_plus_5 =", wrapper)
print("first n where n*2 + wrapper exceeds INT_MAX =",
      (int_max - wrapper) // 2 + 1)
print("first n where n*2 + 1 exceeds uint64 SIZE_MAX =",
      (size_max - 1) // 2 + 1)
print("first n where n*2 + wrapper exceeds uint64 SIZE_MAX =",
      (size_max - wrapper) // 2 + 1)

for n in [int_max, (int_max - wrapper) // 2 + 1]:
    mathematical = n * 2 + wrapper
    print("n =", n, "mathematical Ivy query allocation =", mathematical,
          "int32 modulo =", mathematical & int_max)
PY

Repository: IvorySQL/IvorySQL

Length of output: 540


🏁 Script executed:

#!/bin/bash
set -eu

python3 - <<'PY'
wrapper = len("select * from get_parameter_description(") + 5
int_max = 2**31 - 1
size_max = 2**64 - 1

print("wrapper_length_plus_5 =", wrapper)
print("first n where n*2 + wrapper exceeds INT_MAX =",
      (int_max - wrapper) // 2 + 1)
print("first n where n*2 + 1 exceeds uint64 SIZE_MAX =",
      (size_max - 1) // 2 + 1)
print("first n where n*2 + wrapper exceeds uint64 SIZE_MAX =",
      (size_max - wrapper) // 2 + 1)

for n in [int_max, (int_max - wrapper) // 2 + 1]:
    mathematical = n * 2 + wrapper
    print("n =", n,
          "mathematical Ivy query allocation =", mathematical,
          "int32 modulo =", mathematical & int_max)
PY

Repository: IvorySQL/IvorySQL

Length of output: 540


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- exact frontend allocator behavior ---'
sed -n '1,70p' src/common/fe_memutils.c
sed -n '1,45p' src/include/common/fe_memutils.h

printf '%s\n' '--- PQExpBuffer structure and growth limit ---'
rg -n -C 12 'typedef struct PQExpBufferData|struct PQExpBufferData|enlargePQExpBuffer|MaxAllocSize' \
  src/include src/common -g '*.[ch]' -g '*.c' -g '*.h' | head -n 350

printf '%s\n' '--- psql query buffer declaration and lifecycle ---'
rg -n -C 10 'query_buf\s*=|PQExpBuffer\s+query_buf|createPQExpBuffer\(\)' \
  src/bin/psql/mainloop.c src/bin/psql/*.c src/bin/psql/*.h \
  src/include -g '*.[ch]' -g '*.c' -g '*.h' | head -n 350

printf '%s\n' '--- public Ivy APIs and query_len assignments ---'
rg -n -C 5 'query_len\s*=|IvyStmtPrepare\s*\(|IvyCreatePreparedStatement\s*\(' \
  src/interfaces/libpq/ivy-exec.c src/interfaces/libpq/libpq-ivy.h \
  src/interfaces/libpq/ivytest -g '*.[ch]' -g '*.c' -g '*.h' | head -n 500

Repository: IvorySQL/IvorySQL

Length of output: 50373


🏁 Script executed:

#!/bin/bash
set -eu

python3 - <<'PY'
# Check whether the psql caller's 1 GiB PQExpBuffer bound can overflow
# strlen(sql) * 2 + 1 in a 64-bit size_t.
max_alloc = 0x3fffffff
size_max = 2**64 - 1
n = max_alloc - 1  # buffer data length cannot exceed the allocation minus NUL
print("max_input_length =", n)
print("escaped_size =", n * 2 + 1)
print("SIZE_MAX =", size_max)
print("size_t_overflow =", n > (size_max - 1) // 2)
PY

Repository: IvorySQL/IvorySQL

Length of output: 267


🏁 Script executed:

#!/bin/bash
set -eu

python3 - <<'PY'
max_alloc = 0x3fffffff
size_max = 2**64 - 1
n = max_alloc - 1
print("max_input_length =", n)
print("escaped_size =", n * 2 + 1)
print("SIZE_MAX =", size_max)
print("size_t_overflow =", n > (size_max - 1) // 2)
PY

Repository: IvorySQL/IvorySQL

Length of output: 267


Fix size handling in both Ivy escaped-query paths.

IvyPreparedStatement.query_len and the local query_len variables use int, although query lengths use size_t. Store lengths as size_t and use checked arithmetic for both wrapper and escaped-query allocations before copying. The src/bin/psql/common.c path is bounded by the PQExpBuffer limit and does not have this size_t overflow.

📍 Affects 2 files
  • src/interfaces/libpq/ivy-exec.c#L3800-L3806 (this comment)
  • src/interfaces/libpq/ivy-exec.c#L4094-L4101
  • src/bin/psql/common.c#L3646-L3646
🤖 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/interfaces/libpq/ivy-exec.c` around lines 3800 - 3806, In
src/interfaces/libpq/ivy-exec.c at lines 3800-3806 and 4094-4101, change
IvyPreparedStatement.query_len and the local query_len variables to size_t, then
add checked arithmetic for doubled-quote and wrapper allocation sizes before
allocating or copying, preserving the existing allocation-error handling. The
src/bin/psql/common.c site at line 3646 requires no direct change because its
PQExpBuffer limit bounds the size_t arithmetic.

@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.

🧹 Nitpick comments (1)
src/bin/psql/mainloop.c (1)

495-495: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Add an AddressSanitizer regression test for this path.

Exercise the psqlplus VARIABLE missing-quote branch with an all-quote input. Confirm that no heap-buffer-overflow occurs and that the diagnostic remains NUL-terminated.

🤖 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/mainloop.c` at line 495, Add an AddressSanitizer regression test
covering the psqlplus VARIABLE missing-quote branch in mainloop.c, using an
input consisting entirely of quote characters. Verify execution produces no
heap-buffer-overflow and that the resulting diagnostic remains NUL-terminated.
🤖 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.

Nitpick comments:
In `@src/bin/psql/mainloop.c`:
- Line 495: Add an AddressSanitizer regression test covering the psqlplus
VARIABLE missing-quote branch in mainloop.c, using an input consisting entirely
of quote characters. Verify execution produces no heap-buffer-overflow and that
the resulting diagnostic remains NUL-terminated.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: baf2a8f7-7e7e-46c9-b260-2f23abb34a5b

📥 Commits

Reviewing files that changed from the base of the PR and between 4fe229c and 25dc70c.

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

@jiaoshuntian

Copy link
Copy Markdown
Collaborator

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

@Aias00

Aias00 commented Aug 12, 2026

Copy link
Copy Markdown
Contributor Author

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

so let they do, it`s fine

@Aias00 Aias00 closed this Aug 12, 2026
@jiaoshuntian jiaoshuntian reopened this Aug 13, 2026
@gaoxueyu
gaoxueyu merged commit b2efe51 into IvorySQL:master Aug 14, 2026
10 checks passed
hs-liuxh pushed a commit to hs-liuxh/IvorySQL that referenced this pull request Sep 2, 2026
…rflow-1554

Fix heap buffer overrun in named-bind query escaping

(cherry picked from commit b2efe51)
hs-liuxh pushed a commit to hs-liuxh/IvorySQL that referenced this pull request Sep 2, 2026
…rflow-1554

Fix heap buffer overrun in named-bind query escaping

(cherry picked from commit b2efe51)
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

3 participants