Repository navigation
Conversation
_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>
Earammak
approved these changes
Dec 2, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.prepare()already logs the statement as text just before, so thePreparing SQL statementline now logs only the size.createdb()/dropdb()log their arguments with%sandPyUnicode_AsUTF8(), as Fix DLL load failure on Windows , update workflow and simplify sdist packaging #1053 does.zload_begin(), including the__MVS__branches) frees what it allocated and returns with theUnicodeEncodeErrorset. Debug log lines that converted the argument use a helper that leaves no exception pending.BufferLengthplus a terminator, and an explicitsizeis honoured. When the indicator reports truncation,callproc()andfetch_callproc()decode only what the driver wrote.SQL_NTS), that length is passed asBufferLength, and the copy is capped at the slot. The slot length is stored in the parameter node sofetch_callproc()reads array outputs at the same stride. A sized scalarbytesvalue gets a buffer of the larger of its length andsize.SQLUSMALLINTarray ofSQL_API_ODBC3_ALL_FUNCTIONS_SIZE.free_result()callsSQLFreeStmt()withSQL_UNBINDandSQL_RESET_PARAMSafterSQL_CLOSE._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 reportsSQL_NO_TOTAL.result()paths clamp the indicator to the buffer capacity before decoding. The LONG VARCHAR / LONG VARGRAPHICSQLGetData()call gets the allocated size.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 TIMESTAMPTseparator check tests the length first and uses element 10 in thestrlist path.debug()keeps its own copy of the log file name.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.snprintf()with the destination size; the SQLCODE buffer is 24 bytes. These are defensive: I could not reach them with messages Db2 LUW produces.Py_END_ALLOW_THREADS(or just beforePy_BEGIN_ALLOW_THREADSwhere it logs the arguments of the call that follows), with the same text. TheSQLConnectWmessage no longer includes the password,connect()/pconnect()no longer logrepr()of their arguments, and theSQLDriverConnectWline masksPWDandNEWPWDvalues 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):
strthat cannot be encoded raisesUnicodeEncodeErrorfrom every API that takes text, instead of crashing,SystemErroror "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 raisesN params bound not matching M requiredand runs nothing. With nothing bound, it still raisesParameters not bound.callproc()without asizeand with an input shorter than the output, returns the output truncated to the input length; on master this call overflows the buffer.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 aDECIMAL(31,0)array, astrlist timestamp with aTseparator.result()returns the stored bytes for BLOB and binary values over 10240 bytes, and every API returns the whole LOB underSQL_NO_TOTAL. A LONG VARGRAPHIC value at the full column length keeps its last character.MemoryError, instead ofException: Failed to Allocate Memoryor 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 theSQLUSMALLINTlanded in the high half of anint); I could not test this on a big-endian system.debug()(TypeError,UnicodeEncodeError,OSError),get_option()with type 0 on a connection, non-dict options toset_option()/prepare()/exec_immediate()(the messageconnect()already uses), a non-strprocedure name incallproc(), non-string user or password inconnect_coordinated().fetch_assoc()/fetch_both()raiseUnicodeDecodeErrorfor a column name that cannot be decoded.Binding Errorinstead ofSystemError, andexecute_many()no longer leaves the connection in chaining state.Preparing SQL statementshows only the size;connect()/pconnect()no longer logReceived arguments; on connection close theSQLDisconnect/SQLFreeHandlelines 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_6803runs only against Db2 LUW,test_6806skips when the client code page is not 1208, and the__buffer__cases intest_6802andtest_6809need Python 3.12 or later.Testing (Linux x86_64, Python 3.13, clidriver v11.5.9, Db2 LUW 11.5.8):
test_6811passes on both, because those overflows cannot be reached from a real server; a harness built from the unmodified functions with-D_FORTIFY_SOURCE=3aborts with*** buffer overflow detected ***on master and runs with the fix. Intest_6812the password checks fail on master; the threaded part passes on both, because the race did not fail visibly in testing.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 insidelibdb2, insecLoadClientAuthPlugin, while connecting.)--enable-debugand 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.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.