Skip to content

stringlib bytearray.join function has the potential to leak memory when used with a custom iterator #112625

Closed

Description

@chilaxan

Bug report

Bug description:

If a custom iterator is passed into bytearray.join, and then it frees the bytearray inside of its __iter__, then memory can be read after it is freed:

# stringlib_join_ReadAfterFree.py

def ReadAfterFree(size, do):
    b = bytearray(size)
    class T:
        def __iter__(self):
            b.clear()
            self.v = do()
            yield b''
            yield b''

    c = b.join(t:=T())
    return memoryview(c).cast('P'), t.v

if __name__ == '__main__':
    leak, obj = ReadAfterFree(bytearray.__basicsize__, lambda: bytearray(8))
    print('bytearray:', obj)
    print('leaked memory of buffer:', leak.tolist())
➜  ~/Desktop/Coding/cpython_source git:(main) ./python.exe ../python/stringlib_join_ReadAfterFree.py
bytearray: bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00')
leaked memory of buffer: [1, 4305259912, 8, 9, 4307812848, 4307812848, 0]

CPython versions tested on:

CPython main branch

Operating systems tested on:

macOS

Linked PRs

Activity

  1. added a commit that references this issue on Dec 2, 2023
  2. added a commit that references this issue on Dec 4, 2023
  3. added 2 commits that reference this issue on Dec 4, 2023
  4. added a commit that references this issue on Dec 4, 2023
  5. serhiy-storchaka commented on Dec 4, 2023

    @serhiy-storchaka
    Member

    Thank you for your report and your PR @chilaxan.

  6. added
    3.11only security fixes
    3.12only security fixes
    3.13only security fixes
    on Dec 4, 2023
  7. added a commit that references this issue on Dec 4, 2023
  8. added a commit that references this issue on Feb 11, 2024
  9. added a commit that references this issue on Sep 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

3.11only security fixes3.12only security fixes3.13only security fixestype-bugAn unexpected behavior, bug, or error

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions