Skip to content

gh-157227: _remote_debugging: Validate lists and tuples in write_sample - #157228

Open
maurycy wants to merge 2 commits into
python:mainfrom
maurycy:fix-remote-debugging-writer-validation
Open

gh-157227: _remote_debugging: Validate lists and tuples in write_sample#157228
maurycy wants to merge 2 commits into
python:mainfrom
maurycy:fix-remote-debugging-writer-validation

Conversation

@maurycy

@maurycy maurycy commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

See #157227 for more details

Basically, BinaryWriter.write_sample() only checks whether stack_frames is a list, and does PyList_GET_ITEM() / PyStructSequence_GET_ITEM() all the way. The PR adds a check for these containers.

Now it's graceful:

maurycy@gimel cpython (fix-remote-debugging-writer-validation aec95c2*) % ./python.exe 
Python 3.16.0a0 (heads/fix-remote-debugging-writer-validation-dirty:aec95c21726, Sep  9 2026, 20:) [Clang 21.0.0 (clang-2100.1.1.101)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import _remote_debugging
>>> _remote_debugging.BinaryWriter("/tmp/o.bin", 1000, 1000000).write_sample([42], 2000)
Traceback (most recent call last):
  File "<python-input-1>", line 1, in <module>
    _remote_debugging.BinaryWriter("/tmp/o.bin", 1000, 1000000).write_sample([42], 2000)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^
TypeError: interp_info must be a tuple of at least 2 items
>>> 

instead of segmentation fault.

} \
} while (0)

#define CHECK_TUPLE_ITEMS(obj, n) do { \

@maurycy maurycy Sep 9, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Truth be told, we reinvent similar check over and over:

#define CHECK_LIST_OR_TUPLE(v) \
if (!PyList_Check(v) && !PyTuple_Check(v)) { \
PyErr_SetString(PyExc_TypeError, \
#v " must be a list or a tuple"); \
return NULL; \
}

#define CHECK_LIST_OR_TUPLE(v) \
do { \
if (!PyList_Check(v) && !PyTuple_Check(v)) { \
PyErr_SetString(PyExc_TypeError, \
#v " must be a list or a tuple"); \
return NULL; \
} \
} while (0)

Sometimes without a macro:

/* We allow the state tuple to be longer than 4, because we may need
someday to extend the object's state without breaking
backward-compatibility. */
if (!PyTuple_Check(state) || PyTuple_GET_SIZE(state) < 4) {
PyErr_Format(PyExc_TypeError,
"%.200s.__setstate__ argument should be 4-tuple, got %.200s",
Py_TYPE(self)->tp_name, Py_TYPE(state)->tp_name);
return NULL;
}

cpython/Python/_warnings.c

Lines 450 to 465 in 9a75080

tmp_item = PyList_GET_ITEM(filters, i);
if (!PyTuple_Check(tmp_item) || PyTuple_GET_SIZE(tmp_item) != 5) {
PyErr_Format(PyExc_ValueError,
"warnings.%s item %zd isn't a 5-tuple", list_name, i);
result = false;
break;
}
/* Python code: action, msg, cat, mod, ln = item */
Py_INCREF(tmp_item);
action = PyTuple_GET_ITEM(tmp_item, 0);
msg = PyTuple_GET_ITEM(tmp_item, 1);
cat = PyTuple_GET_ITEM(tmp_item, 2);
mod = PyTuple_GET_ITEM(tmp_item, 3);
ln_obj = PyTuple_GET_ITEM(tmp_item, 4);

Py_ssize_t num_interpreters = PyList_GET_SIZE(stack_frames);
for (Py_ssize_t i = 0; i < num_interpreters; i++) {
PyObject *interp_info = PyList_GET_ITEM(stack_frames, i);
CHECK_TUPLE_ITEMS(interp_info, 2);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We validate as we go, so a bad thread in the middle leaves the earlier threads already written and total_samples bumped even though write_sample raised. Should we walk and validate the whole structure first so this is all-or-nothing? Otherwise the caller has no way to recover from the TypeError.


PyObject *interp_id_obj = PyStructSequence_GET_ITEM(interp_info, 0);
PyObject *threads = PyStructSequence_GET_ITEM(interp_info, 1);
CHECK_LIST(threads);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This narrows the hole but does not close it. PyLong_AsLong(status_obj) goes through _PyNumber_Index, so an __index__ that mutates the same list re-enters us while we still hold a cached size and a borrowed thread_info:

threads = []
class Evil:
    def __index__(self):
        del threads[:]
        return 0
threads.extend([(1, Evil(), []), (2, 0, [])])
_remote_debugging.BinaryWriter("/tmp/o.bin", 1000, 0, compression=0).write_sample([(0, threads)], 2000)

This still segfaults on PyList_GET_ITEM(threads, 1) because del threads[:] frees ob_item. writer_intern_string has the same problem via PyObject_Hash. If we want to claim write_sample is safe against arbitrary input we need strong references to the containers (or to re-read the sizes), not only a type check up front. Happy to take this as a follow-up, but then let's not close the issue with this PR.

int32_t end_column = LOCATION_NOT_AVAILABLE;

if (location != Py_None) {
CHECK_TUPLE_ITEMS(location, 4);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

normalize_location() in Lib/profiling/sampling/collector.py accepts an int location (a bare lineno) and binary_collector.py hands stack_frames straight to write_sample, so this now raises where the other collectors work. Do we want a PyLong_Check(location) case here too, or is that branch in normalize_location() dead and we should drop it instead?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants