Skip to content

Use-after-free in bytearray.take_bytes() with a reentrant __index__ #153570

Closed

Description

@tonghuaroot

Bug report

Bug description:

The C implementation of bytearray.take_bytes() reads the size before calling
the argument's __index__(), then uses that stale size for the bounds check and
the buffer reads, so an __index__ that resizes the bytearray reads freed
memory (a use-after-free; segfaults on a debug build).

b = bytearray(b'A' * (16 * 1024 * 1024))
class Evil:
    def __index__(self):
        b.clear()
        return 8 * 1024 * 1024
b.take_bytes(Evil())   # use-after-free

bytearray.__setitem__ re-reads the size after __index__ (GH-91153).

CPython versions tested on:

3.15, 3.16

Operating systems tested on:

macOS

Linked PRs

Activity

  1. added
    type-bug
    on Jul 11, 2026
  2. added
    interpreter-core
    on Jul 12, 2026
  3. added a commit that references this issue on Jul 24, 2026
  4. added
    3.15
    3.16
    on Jul 24, 2026
  5. added a commit that references this issue on Jul 24, 2026
  6. added a commit that references this issue on Aug 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.153.16interpreter-coretype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions