py/objdeque.c: Fix buffer overflow in deque_subscr(). #16108
Merged
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.
Summary
This PR resolves an off-by-one buffer overflow in py/objdeque.c when using deque with indexing. The error occurs when appending data beyond the size of the allocated buffer (discarding items from the opposite end) without overflow checking.
Reproduction
The following code demonstrates the issue on all boards/ports:
Expected Output
Actual Output
Root Cause
The issue arises from an off-by-one error in
deque_subscr()
. Ifindex_val
equalsself->alloc
, the necessary index correctionindex_val -= self->alloc
is skipped, leading to an out-of-bounds access whenself->items[index_val]
is called. Sinceself->items
has a length ofself->alloc
, this results in a buffer overflow.This fix ensures that the index correction is applied whenever
index_val >= self->alloc
, preventing access beyond the allocated buffer size.Testing
Tested on unix and esp32 port.