Skip to content

Fix memory-safety bugs in parameter binding, fetch and debug logging - #1095

Open
rpcope1 wants to merge 14 commits into
ibmdb:masterfrom
rpcope1:fix/memory-safety
Open

rpcope1 wants to merge 14 commits into
ibmdb:masterfrom
rpcope1:fix/memory-safety

Conversation

@rpcope1

@rpcope1 rpcope1 commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

This fixes the crashes, heap overflows and leaks described in issue #1094. They are in one PR because most of them touch the same functions (_python_ibm_db_bind_data(), the execute and fetch paths), so separate PRs would conflict with each other. There is one commit per problem. Each commit builds on its own, has its own regression test and can be reviewed on its own. A squash merge is fine.

  • Do not format SQLWCHAR text with %ls in debug log messages. prepare() already logs the statement as text just before, so the Preparing SQL statement line now logs only the size. createdb()/dropdb() log their arguments with %s and PyUnicode_AsUTF8(), as Fix DLL load failure on Windows , update workflow and simplify sdist packaging #1053 does.
  • Raise UnicodeEncodeError for str input that cannot be converted. Both conversion helpers check their intermediate results, and every caller (connect, set_option, the createdb family, prepare, exec_immediate, callproc, the catalog functions, scalar and list parameters, zload_begin(), including the __MVS__ branches) frees what it allocated and returns with the UnicodeEncodeError set. Debug log lines that converted the argument use a helper that leaves no exception pending.
  • Size INOUT/OUT string parameter buffers to the BufferLength given to the driver. The buffer is always at least BufferLength plus a terminator, and an explicit size is honoured. When the indicator reports truncation, callproc() and fetch_callproc() decode only what the driver wrote.
  • Fix bind buffer overflows for list and sized bytes parameters. Each list slot is sized to the longest item (plus a terminator where the slot is bound with SQL_NTS), that length is passed as BufferLength, and the copy is capped at the slot. The slot length is stored in the parameter node so fetch_callproc() reads array outputs at the same stride. A sized scalar bytes value gets a buffer of the larger of its length and size.
  • Fix stack overflow in check_function_support(). The output is a SQLUSMALLINT array of SQL_API_ODBC3_ALL_FUNCTIONS_SIZE.
  • Unbind columns and parameters in free_result before freeing buffers. free_result() calls SQLFreeStmt() with SQL_UNBIND and SQL_RESET_PARAMS after SQL_CLOSE.
  • Fix LOB length handling in result() and fetch continuation reads. A new helper, _python_ibm_db_get_data_rest(), reads the rest of a LOB. It tracks capacity and received length separately and grows the buffer when the CLI reports SQL_NO_TOTAL.
  • Clamp returned lengths to the bound buffer on fetch. The column fetch, rowset fetch and result() paths clamp the indicator to the buffer capacity before decoding. The LONG VARCHAR / LONG VARGRAPHIC SQLGetData() call gets the allocated size.
  • Fix crashes and stale binds in bind_param, execute and execute_many. Py_XDECREF() for the cached value; execute_many() skips rows that are too short when it looks ahead for a type; execute() returns its parameter-count error straight away; the TIMESTAMP T separator check tests the length first and uses element 10 in the str list path.
  • Validate arguments in debug, get_option, set_option and callproc. Each case returns NULL with an exception. debug() keeps its own copy of the log file name.
  • Release buffer views taken when binding binary parameters. The PyObject_GetBuffer() result is checked, the data is copied while the view is held, the view is released, and only the driver's own copies are freed.
  • Fix memory leaks in execute_many(), prepare() and fetched columns.
  • Bound the copies into fixed-size error buffers. snprintf() with the destination size; the SQLCODE buffer is 24 bytes. These are defensive: I could not reach them with messages Db2 LUW produces.
  • Keep the GIL for Python calls and debug logging, and stop logging the password. Every log and error-buffer write that ran with the GIL released now runs just after Py_END_ALLOW_THREADS (or just before Py_BEGIN_ALLOW_THREADS where it logs the arguments of the call that follows), with the same text. The SQLConnectW message no longer includes the password, connect()/pconnect() no longer log repr() of their arguments, and the SQLDriverConnectW line masks PWD and NEWPWD values as ****. The string passed to the driver is unchanged. Since logging now always holds the GIL, debug() frees the file name it replaces.

User-visible changes (valid input otherwise behaves as before, and existing error messages are unchanged except as listed):

  • A str that cannot be encoded raises UnicodeEncodeError from every API that takes text, instead of crashing, SystemError or "Binding Error". execute_many() runs the remaining rows and raises it at the end, as it does for its other row errors. A non-ASCII PARAM_FILE name keeps its current "Binding Error" message.
  • execute() with the wrong number of parameters raises N params bound not matching M required and runs nothing. With nothing bound, it still raises Parameters not bound.
  • A truncated value (fetched, or an INOUT/OUT output) is returned as the part the driver wrote. An INOUT LOB declared larger than 1048576, called through callproc() without a size and with an input shorter than the output, returns the output truncated to the input length; on master this call overflows the buffer.
  • An over-long list item raises the same driver error as the scalar form (CLI0109E, CLI0112E). Some list inputs that failed on master now work: an exactly full item in an INPUT_OUTPUT character array, [10**30, 5] for a DECIMAL(31,0) array, a str list timestamp with a T separator.
  • result() returns the stored bytes for BLOB and binary values over 10240 bytes, and every API returns the whole LOB under SQL_NO_TOTAL. A LONG VARGRAPHIC value at the full column length keeps its last character.
  • A LOB continuation buffer that cannot be allocated raises MemoryError, instead of Exception: Failed to Allocate Memory or an unchecked allocation.
  • check_function_support() with 0 or 999 returns a bool. On big-endian platforms, supported single functions now return True (on master the SQLUSMALLINT landed in the high half of an int); I could not test this on a big-endian system.
  • Wrong-type arguments raise exceptions: debug() (TypeError, UnicodeEncodeError, OSError), get_option() with type 0 on a connection, non-dict options to set_option()/prepare()/exec_immediate() (the message connect() already uses), a non-str procedure name in callproc(), non-string user or password in connect_coordinated(). fetch_assoc()/fetch_both() raise UnicodeDecodeError for a column name that cannot be decoded.
  • A failed buffer export for a binary parameter raises Binding Error instead of SystemError, and execute_many() no longer leaves the connection in chaining state.
  • Debug log: the password no longer appears; Preparing SQL statement shows only the size; connect()/pconnect() no longer log Received arguments; on connection close the SQLDisconnect/SQLFreeHandle lines come after those calls. Other message text is unchanged.

Closes #1094

Added tests, one per commit:

  • test_6798_DebugLogText.py, test_6800_LoneSurrogateInput.py, test_6801_InoutParamBufferSize.py, test_6802_BindBufferSize.py, test_6803_CheckFunctionSupportAll.py, test_6804_FreeResultRebind.py, test_6805_ResultLargeLob.py, test_6806_TruncatedFetchLength.py, test_6807_BindExecuteErrors.py, test_6808_ArgumentValidation.py, test_6809_BinaryBindRefcount.py, test_6810_StatementCacheLeaks.py, test_6811_LongDiagnostics.py, test_6812_ThreadedConnectLog.py.
  • test_6803 runs only against Db2 LUW, test_6806 skips when the client code page is not 1208, and the __buffer__ cases in test_6802 and test_6809 need Python 3.12 or later.

Testing (Linux x86_64, Python 3.13, clidriver v11.5.9, Db2 LUW 11.5.8):

  • Each new test fails or crashes on master and passes with its commit, with two exceptions. test_6811 passes on both, because those overflows cannot be reached from a real server; a harness built from the unmodified functions with -D_FORTIFY_SOURCE=3 aborts with *** buffer overflow detected *** on master and runs with the fix. In test_6812 the password checks fail on master; the threaded part passes on both, because the race did not fail visibly in testing.
  • Every commit in the series builds on its own and passes its own test.
  • Valgrind (PYTHONMALLOC=malloc) reports no invalid reads or writes and no errors in ibm_db code on any of the new tests. (Each run reports one uninitialised read inside libdb2, in secLoadClientAuthPlugin, while connecting.)
  • Under jemalloc 5.3.0 built with --enable-debug and guard pages (MALLOC_CONF=san_guard_small:1,san_guard_large:1), a script that prepares and frees 200 long statements segfaults on master and completes with this branch.
  • The full sync suite fails the same set of tests before and after this branch (15 failures and 45 errors on both, against 3.4.0). Those failures are environment gaps in my test database (missing sample tables, procedures and files).
  • Compiler warnings: 251 on master, 248 with this branch.

Since several of these are crashes or heap overflows reachable with ordinary input, it would be good to get them into a patch release (3.4.1) soon after merging.

_python_ibm_db_do_prepare(), _python_ibm_db_createdb() and
_python_ibm_db_dropdb() formatted SQLWCHAR buffers with %ls, which
expects wchar_t. Where wchar_t is 4 bytes (Linux, macOS, 64-bit AIX),
snprintf read the 2-byte buffers two characters at a time and past
their end, whether or not debug logging was on, and the debug log got
unreadable text. This is the same problem ibmdb#1053 fixed for the connect
messages.

prepare() already logs the statement as text before calling
_python_ibm_db_do_prepare(), so that message now logs only the size.
createdb() and dropdb() log their arguments with %s and
PyUnicode_AsUTF8(), as ibmdb#1053 does.

Add a regression test.

Signed-off-by: Robert Cope <robert@copesystems.com>
A str can hold a lone surrogate, for example one produced by
json.loads('"\ud800"'). Such a string has no UTF-16 or UTF-8 form, so
getUnicodeDataAsSQLWCHAR() and getUnicodeDataAsSQLCHAR() fail and
return NULL with UnicodeEncodeError set. 59 of their 63 callers did
not check for that. Binding a parameter copied from the NULL buffer and
crashed execute(), bind_param() + execute() and execute_many(); prepare()
and tables() crashed; other calls passed NULL to the CLI or returned
with the exception still set (SystemError), and connect() went on with
a NULL connection string. getUnicodeDataAsSQLCHAR() (z/OS) also used
the failed result itself.

Both helpers now check their own intermediate results, and every caller
checks the result, releases what it allocated and returns its error
result, leaving the UnicodeEncodeError set. For a parameter,
_python_ibm_db_bind_data() returns a new BIND_CONVERSION_ERROR code, so
execute() raises the UnicodeEncodeError instead of a "Binding Error"
(other binding errors keep their message), and execute_many() raises it
once the batch has run, as it does for its other row errors. Debug log
lines that format these arguments no longer leave an exception set when
the text cannot be encoded.

Add a regression test.

Signed-off-by: Robert Cope <robert@copesystems.com>
…the driver

For SQL_PARAM_OUTPUT and SQL_PARAM_INPUT_OUTPUT parameters bound from a
str, _python_ibm_db_bind_data() raised the BufferLength passed to
SQLBindParameter() to (param_size + 1) * sizeof(SQLWCHAR), but widened
the buffer only when the input length in bytes was no more than
param_size in characters. For inputs longer than half the declared size
(17 to 31 characters for a VARCHAR(32)), the buffer kept its input-sized
allocation and the driver wrote the output value past its end. An
explicit size argument and SQL_XML parameters hit the same mismatch, and
when the column size guard skipped widening, the larger BufferLength
was kept.

The buffer for an OUTPUT or INPUT_OUTPUT parameter is now at least
BufferLength plus a terminator. An explicit size is honoured even when
the column size is 0 or too large to trust. Without one, when the column
size guard skips widening, BufferLength is reduced to the size of the
existing buffer.

When the indicator reports a longer, truncated value, callproc() and
fetch_callproc() now decode only what the driver wrote: whole SQLWCHAR
units up to BufferLength less the terminator for character data bound
from a str, BufferLength less the terminator for character data bound
from bytes, and BufferLength for binary data. In fetch_callproc() this
covers every scalar CHAR, VARCHAR, CLOB, DBCLOB, BINARY, VARBINARY,
LONGVARBINARY, BLOB and DECIMAL output that reads the indicator.

Signed-off-by: Robert Cope <robert@copesystems.com>
_python_ibm_db_bind_data() copies each item of a list parameter into a
fixed-size slot: 31 bytes for integers bound to BIGINT or DECIMAL; for
Decimal values, 31 bytes for DECIMAL (the parameter size for DECFLOAT);
and the parameter size for bytes. A longer item was copied past the
end of its slot and, for the last item, past the end of the heap
buffer. Integer items, and bytes items of OUTPUT and INPUT_OUTPUT
character arrays, are bound as null-terminated strings, and an item
that filled its slot left no room for the terminator.

For a scalar bytes value bound with bind_param() and an explicit size,
the buffer was allocated as size + 1 bytes and then the whole value was
copied into it.

Size list slots to fit the longest item, plus a terminator for integer
and bytes lists, and pass that as the buffer length, so the database
rejects a value that does not fit as it does for scalar values. Copy
no more than a slot holds, in case an item's str() or buffer returns a
longer value than when the slots were sized. Record the slot length in
the parameter node, and have fetch_callproc() read OUTPUT and
INPUT_OUTPUT array elements at that stride. Allocate the scalar bytes
buffer for the larger of the value length and the size.

Signed-off-by: Robert Cope <robert@copesystems.com>
check_function_support() passed the address of an int as the output array
of SQLGetFunctions(). For SQL_API_ALL_FUNCTIONS (0) the driver writes 100
SQLUSMALLINT values and for SQL_API_ODBC3_ALL_FUNCTIONS (999) it writes
250, overflowing the stack.

Use a SQLUSMALLINT array of SQL_API_ODBC3_ALL_FUNCTIONS_SIZE elements.
Single function ids still return whether that function is supported. For
ids 0 and 999 the result is True if any function is reported as
supported.

Signed-off-by: Robert Cope <robert@copesystems.com>
free_result() closed the cursor with SQLFreeStmt(SQL_CLOSE) and then
freed the column buffers, indicators and parameter storage. SQL_CLOSE
keeps column and parameter bindings, so the CLI still pointed at the
freed memory. Executing the statement again and calling fetch_row(),
which does not rebind columns, made SQLFetch write into the freed
buffers and could crash the process.

Call SQLFreeStmt with SQL_UNBIND and SQL_RESET_PARAMS after SQL_CLOSE
succeeds, before the buffers are freed. The other callers of
_python_ibm_db_free_result_struct free the statement handle first, so
they are not affected.

Add a regression test.

Signed-off-by: Robert Cope <robert@copesystems.com>
result() on a BLOB or binary column larger than 10240 bytes built the
return value from the size of the continuation buffer instead of the
number of bytes received, so it returned the data followed by about
10 KB of uninitialised heap memory.

The LOB continuation reads in result(), the fetch_*() functions and
fetchmany() also used the SQLGetData length indicator as an allocation
size. When CLI returns SQL_NO_TOTAL (-4) instead, for example for LOBs
over 1 MB with StreamGetData=1, the new buffer was smaller than the data
already copied into it, which corrupted the heap, crashed, or truncated
the value. Two of these allocations were also not checked.

Read the rest of a LOB in one helper that tracks the buffer capacity and
the received length separately, grows the buffer until SQLGetData stops
reporting truncation, and raises MemoryError if the buffer cannot grow.

Signed-off-by: Robert Cope <robert@copesystems.com>
When a fetched value is truncated, the CLI sets the length indicator to
the full length of the value, not the number of bytes written into the
buffer. The fetch paths passed that length straight to the Python
constructors, so they read past the bound buffer: fetch_tuple() and
friends read past the column buffer, and fetchmany() returned bytes
from the next row's slot or past the end of the rowset buffer.

This happens, for example, with MAPGRAPHICDESCRIBE=1 and WCHAR_NO: a
VARGRAPHIC(5) column is described as VARCHAR(10) and bound with 11
bytes, but five Thai characters take 15 bytes in UTF-8.

Clamp the length to the bound buffer's capacity, less the terminator
for character data, before decoding in the column fetch, rowset fetch
and result() paths. The truncated value is the part the driver wrote
into the buffer, and the truncation warning is reported as before.

Also pass the allocated size of the LONG VARCHAR / LONG VARGRAPHIC
SQLGetData buffer, (size + 1) * sizeof(SQLWCHAR), instead of one byte
less. With the odd length, a LONG VARGRAPHIC value that filled the
column came back with its last character corrupted; it now comes back
whole.

Signed-off-by: Robert Cope <robert@copesystems.com>
Four bugs in the parameter binding and execute paths:

- bind_param() on a statement whose parameters were last bound by
  execute(stmt, tuple) replaced the cached node with Py_DECREF on a NULL
  var_pyvalue and crashed. This happens after an execute() that fails,
  for example on a duplicate key. Use Py_XDECREF.
- execute_many() looked ahead at later rows to find the type of a None
  value without checking that those rows were long enough, so
  ((1, None), ()) read past the end of the empty tuple and crashed.
  Skip rows that are too short; the row length check still reports them.
- execute() with more parameters than the statement has, or with fewer
  parameters bound by bind_param() than the statement has, set an
  exception and carried on. Inside a transaction it ran the statement
  with the parameter buffers freed by the previous execute, inserting a
  stale row, and then failed with SystemError. Return the error straight
  away. With nothing bound at all, execute() still raises "Parameters
  not bound".
- A bytes value shorter than 11 bytes bound to a TIMESTAMP read, and
  could write, svalue[10] past the end of its buffer. The list (array)
  path for str timestamps checked element 20 for the ISO 8601 'T'
  separator instead of element 10, so such arrays failed with CLI0113E.
  Check the length first and use element 10, as the scalar str path does.
  In the list paths, check element 10 only when it was copied into the
  slot, so a list bound with a precision too small for a timestamp does
  not read past it; the str list path also sends only the copied part
  instead of the whole value's length.

Signed-off-by: Robert Cope <robert@copesystems.com>
Several APIs crashed or read invalid memory when given an argument of
the wrong type:

- debug() continued after PyArg_ParseTuple() or PyUnicode_AsUTF8()
  failed, dereferencing NULL, and returned None with an exception set.
  It also kept a pointer into the argument's UTF-8 buffer as the log
  file name, so later log lines could be written to whatever file name
  the freed memory then held.
- get_option() with type 0 cast any object to a statement handle.
- set_option(), prepare() and exec_immediate() passed options that were
  not a dict to PyDict_Keys() and then PyList_Size(NULL).
- callproc() with a procedure name that was not a str used it as one.
- connect_coordinated() used the result of PyUnicode_FromObject() for
  the user and password without checking it.
- createdb() checked codesetObj where it meant modeObj, so a mode that
  could not be converted was used as NULL.
- fetch_assoc() and fetch_both() passed a NULL key to PyDict_SetItem()
  when a column name was not valid UTF-8.

Return NULL with an exception in each case. debug() now keeps its own
copy of the log file name. A replaced copy is not freed, because
LogMsg() can run without the GIL and another thread may still be reading
it; setting the same name again reuses the copy. Unencodable file names
raise UnicodeEncodeError. Options that are not a dict raise the message
connect() already uses, and get_option() raises the message the other
statement APIs use. A connect_coordinated() database that is not a
string still raises "Database parameter is required".

Add a regression test.

Signed-off-by: Robert Cope <robert@copesystems.com>
_python_ibm_db_bind_data() called PyObject_GetBuffer() on values bound
to BLOB, BINARY and VARBINARY parameters without checking the result,
and never called PyBuffer_Release(). Every such bind leaked a reference
to the bound bytes object. In a list whose first value is a str, a later
bytes value had its own storage passed to PyMem_Del(), an invalid free
that can crash the interpreter.

Check the result, copy the data while the view is held, then release
the view. Free only the copies the driver owns. The scalar bytes branch
now also frees the copy left by an earlier execute, as the other
branches already do. A failed buffer export raises the usual binding
error, and the export's own exception is cleared so that execute_many()
does not carry on with it pending.

Signed-off-by: Robert Cope <robert@copesystems.com>
execute_many() replaced the statement's parameter cache without freeing
the previous one, so every call leaked the parameter nodes and their
buffers. Within a call, binding a BIGINT, DECIMAL, DATE, TIME or
TIMESTAMP value allocated a new buffer for every row without freeing
the one from the row before. execute_many() now resets the parameter
bindings and releases the previous cache with
_python_ibm_db_clear_param_cache(), and those bind paths free the old
buffer first, as the string and Unicode paths already do.

BINARY, VARBINARY and LONG VARBINARY column buffers were never freed
when a result was freed or a single-row binding was dropped for a
rowset fetch. They are now freed along with the character buffers.

prepare() leaked the statement object, its CLI statement handle and a
reference to the connection whenever preparation failed, except for a
rejected statement option. It now releases the statement on every
failure. A new statement object starts with no CLI handle (-1), so
releasing it before SQLAllocHandle() has set one frees nothing.

getSQLWCharAsPyUnicodeObject() leaked a reference to sys and to
sys.maxunicode on every value it decoded.

Signed-off-by: Robert Cope <robert@copesystems.com>
_build_client_err_list() copied a message into a DB2_MAX_ERR_MSG_LEN
buffer with strcpy(), but its callers build that message by prefixing
text to the statement error message, so it can be up to about 50 bytes
longer than the buffer. The column-information error path in
result() did the same into the statement error
message buffer. The SQLCODE text in _python_ibm_db_check_sql_errors()
was sprintf()ed into a 16-byte buffer, and estrndup() clamped the
length but then copied the whole string with strcpy().

Use snprintf() with the destination size for each copy and size the
SQLCODE buffer to hold any int. Over-long messages are truncated.
Messages that fit are unchanged.

Signed-off-by: Robert Cope <robert@copesystems.com>
… password

connect() through SQLConnectW (a database name without '=') called
PyUnicode_GetLength() and PyUnicode_AsUTF8() with the GIL released, and
formatted the password into its debug message. The lengths are now
computed before the GIL is released, and the message logs the uid but
not the password or its length.

The password also reached the debug log in two other ways. connect()
and pconnect() logged repr() of their arguments on entry, and they no
longer do. The SQLDriverConnectW message logged the connection string
as given, and it now shows the value of each PWD and NEWPWD keyword
as ****, whatever whitespace (such as a tab) is around the keyword. The
string passed to the driver is unchanged.

Thirty snprintf(messageStr, ...) calls, their LogMsg() calls and nine
_python_ibm_db_check_sql_errors() calls also ran with the GIL released.
messageStr and the error globals are shared by the whole process, so
threads wrote to them at the same time. Each of these now runs just
after Py_END_ALLOW_THREADS, or just before Py_BEGIN_ALLOW_THREADS where
it logs the arguments of the call that follows, with the same text.

With logging now always done under the GIL, debug() frees the log file
name it replaces instead of keeping every old copy.

Add a regression test.

Signed-off-by: Robert Cope <robert@copesystems.com>
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.

Crashes, heap overflows and leaks in parameter binding, fetch and debug logging

2 participants