Repository navigation
Fix heap buffer overrun in named-bind query escaping - #1569
Conversation
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
📝 WalkthroughWalkthroughThe changes fix buffer sizing for escaped quotes and terminating NUL bytes. Named-bind replacement helpers now clean up and report errors when allocation fails. ChangesQuery buffer safety
Estimated code review effort: 2 (Simple) | ~10 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 inconclusive)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
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.
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
src/bin/psql/common.csrc/interfaces/libpq/ivy-exec.c
| 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; | ||
| } |
There was a problem hiding this comment.
🔒 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 500Repository: 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 700Repository: 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}")
PYRepository: 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}")
PYRepository: 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 500Repository: 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)
PYRepository: 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)
PYRepository: 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 500Repository: 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)
PYRepository: 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)
PYRepository: 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-L4101src/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.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/bin/psql/mainloop.c (1)
495-495: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick winAdd an AddressSanitizer regression test for this path.
Exercise the psqlplus
VARIABLEmissing-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
📒 Files selected for processing (1)
src/bin/psql/mainloop.c
|
It looks like they are doing the same thing. #1568 |
so let they do, it`s fine |
…rflow-1554 Fix heap buffer overrun in named-bind query escaping (cherry picked from commit b2efe51)
…rflow-1554 Fix heap buffer overrun in named-bind query escaping (cherry picked from commit b2efe51)
Summary
Fixes #1554: the escaped-query buffer in the named-bind path was allocated as
2 * query_lengthbytes. When the input query consists entirely of single quotes, the escaping loop writes exactly2 * query_lengthbytes 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()insrc/interfaces/libpq/ivy-exec.c— allocate2 * len + 1, compute withsize_tarithmetic, checkmalloc()failure (previously unchecked, would crash on OOM).Ivyreplacenamebindtoposition2()insrc/interfaces/libpq/ivy-exec.c— same fix; the+1also makes empty input produce a valid one-byte empty string buffer instead of a NUL write through a zero-lengthmalloc(0).get_hostvariables()insrc/bin/psql/common.c— same buffer overrun confirmed; allocate2 * len + 1(empty input was already safe here becausepg_malloc0(0)maps to a 1-byte allocation).psqlplus VARIABLEmissing-termination-quote handling insrc/bin/psql/mainloop.c— same overrun: a quote-onlyinit_valuefills the2 * lenbuffer and the terminating NUL lands one byte past; allocate2 * len + 1.Reviewed other quote-doubling sites for the same pattern:
pg_upgrade/util.c,psql/command.candtab-complete.in.calready size with+2/+3;fe_utils/string_utils.cuses a growing PQExpBuffer;fe-connect.candtsearchcmds.care parsers, not escaping copies.Test plan
make -C src/interfaces/libpq ivy-exec.o,make -C src/bin/psql common.oandmake -C src/bin/psql mainloop.ocompile cleanly with the changes.ivy_sema.cbuild error on macOS (separate branchfix-ivy-sema-include-guards); the changed translation units themselves compile cleanly.'') to confirm the overrun is gone.Summary by CodeRabbit