Skip to content

fix out-of-bounds access in array_caster on mutating __len__ - #6220

Open
sayed0200 wants to merge 1 commit into
pybind:masterfrom
sayed0200:stl-array-caster-len-oob
Open

sayed0200 wants to merge 1 commit into
pybind:masterfrom
sayed0200:stl-array-caster-len-oob

Conversation

@sayed0200

Copy link
Copy Markdown
Contributor

Description

The std::array/std::valarray type caster in include/pybind11/stl.h reads the length of the incoming Python object twice from two independent __len__ calls: once to size its storage (resize(l.size()), or the l.size() != Size check) and again when the range-for over the sequence fetches its end() sentinel. A caller can pass an object whose __len__ returns different values on successive calls, so the count driving the writes no longer matches the storage that was allocated. In the resizable path the loop then writes (*value)[ctr++] past the end of the resized valarray, and in the fixed-size path vector_to_array<ArrayType, Size> reads past the end of a temp vector that ended up shorter than Size. I hit both while fuzzing the STL casters with a sequence object that mutates its reported length between calls, and AddressSanitizer flags a heap-buffer-overflow write for the valarray case and an OOB read (SEGV) for the array case. The fix snapshots the length once and bounds the write loop against it, and rejects a sequence that produced fewer than Size elements before handing temp to vector_to_array, so the conversion stays inside convert_elements and never trusts the second length. A regression test drives both paths with a mutating-__len__ object and segfaults on the current headers.

Suggested changelog entry:

  • Fixed an out-of-bounds read/write in the std::array/std::valarray caster when a Python object reports an inconsistent length across __len__ calls during conversion.

This branch has not been deployed

No deployments
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.

1 participant