Skip to content

BufferedReader and BufferedWriter hand owner-less memoryviews to Python-level raw objects (use-after-free) #162658

Duplicate

Description

@xuziqiang98

Crash report

When the raw object of a BufferedReader or BufferedWriter is written in Python, _io passes it a memoryview that does not keep the backing storage alive. _bufferedreader_raw_read() and _bufferedwriter_raw_write() fill a Py_buffer with obj == NULL, wrap it with PyMemoryView_FromBuffer() and call raw.readinto() / raw.write() with it (view.obj is None). If the callback keeps a reference to the view it was given, the view is dangling as soon as the owner releases the storage.

Three ways to hit it, each reported by ASan as heap-use-after-free on 3.11.18, 3.12.16, 3.13.18, 3.14.10, 3.15.2, 3.16.0a2 and main (4b66b87), 3 runs each:

  1. read1(): its scratch buffer is a temporary (a PyBytesWriter on 3.15+, a bytes object before) that is released when read1() returns, so the view dangles immediately.
  2. read(n) with n larger than twice the buffer size: _bufferedreader_read_generic() reads straight into a temporary buffer the same way.
  3. write(b) with b larger than the buffer: the view points into the caller's bytes object.

Reproducer

import io

saved = []


class Raw:
    closed = False

    def readable(self):
        return True

    def flush(self):
        pass

    def close(self):
        pass

    def readinto(self, buf):
        saved.append(buf)             # keep the view; nothing else owns the storage
        memoryview(b"x").tobytes()    # 3.15+: so that read1() really frees it below
        return 0


br = io.BufferedReader(Raw(), 100)
br.read1(100)                         # back in C: the temporary buffer is released

v = saved[0]                          # still a writable memoryview, len == 100
print("v[0] = %d" % v[0])             # use-after-free read

Output

3.15.2, built from the official tarball with --with-address-sanitizer (compiled with -fno-optimize-sibling-calls so that the read1() frame shows up in the free stack):

ERROR: AddressSanitizer: heap-use-after-free
READ of size 1 at 0x51200000e8c0 thread T0
    #0 unpack_single Objects/memoryobject.c:1828:20
    #1 PyObject_GetItem Objects/abstract.c:163:26
    ...
0x51200000e8c0 is located 0 bytes inside of 280-byte region [0x51200000e8c0,0x51200000e9d8)
freed by thread T0 here:
    #0 free
    #1 _PyFreeList_Free Include/internal/pycore_freelist.h:70:9
    #2 PyBytesWriter_Discard Objects/bytesobject.c:3860:5
    #3 PyBytesWriter_FinishWithSize Objects/bytesobject.c:3917:5
    #4 _io__Buffered_read1_impl Modules/_io/bufferedio.c:1091:12
    #5 _io__Buffered_read Modules/_io/clinic/bufferedio.c.h:721:20

Up to 3.14 the freed storage is the bytes object that read1() allocated, released by _PyBytes_Resize() in _io__Buffered_read1_impl() when the read is short.

The memoryview(b"x").tobytes() line matters on 3.15+ only: it keeps the one-slot bytes_writers freelist busy, so that read1() frees the writer instead of parking it on the freelist. Without the line ASan does not report on 3.15+, because the writer is reused rather than returned to the allocator; the view is still live.

Without a sanitizer, reading through the stale view returns whatever is in that memory now and writing through it overwrites it. On 3.12.3, 3.13.5 and 3.15.0 a write through the stale view showed up in a freshly allocated bytes object.

read() and write()

Two more snippets that report heap-use-after-free on the same versions

read() straight into the scratch buffer:

import io

saved = []


class Raw:
    closed = False

    def readable(self):
        return True

    def flush(self):
        pass

    def close(self):
        pass

    def readinto(self, buf):
        saved.append(buf)
        memoryview(b"x").tobytes()
        return 0


br = io.BufferedReader(Raw(), 8)      # buffer_size = 8
br.read(100)                          # 100 > 2 * 8: direct read into the scratch buffer
v = saved[0]
print("v[0] = %d" % v[0])

The free stack ends in _io__Buffered_read_impl() on all of them, through PyBytesWriter_FinishWithSize() on 3.15+ and through _PyBytes_Resize() before.

write() handing out a view of the caller's object:

import io

saved = []


class Raw:
    closed = False

    def writable(self):
        return True

    def flush(self):
        pass

    def close(self):
        pass

    def write(self, b):
        saved.append(b)               # keep the view; view.obj is None
        return len(b)


w = io.BufferedWriter(Raw(), 8)
size = 4096                           # a variable, so that the bytes object is not a constant
w.write(b"A" * size)                  # larger than the buffer: passed to raw.write()
v = saved[0]                          # the bytes object died with the previous statement
print("v[0] = %d (expected 65)" % v[0])
ERROR: AddressSanitizer: heap-use-after-free
READ of size 1 at 0x521000024520 thread T0
    #0 unpack_single Objects/memoryobject.c:1828:20
    #1 PyObject_GetItem Objects/abstract.c:163:26
    ...
0x521000024520 is located 32 bytes inside of 4129-byte region [0x521000024500,0x521000025521)
freed by thread T0 here:
    #1 _Py_Dealloc Objects/object.c:3324:5
    #2 Py_DECREF_MORTAL Include/internal/pycore_object.h:457:9
    ...

CPython versions tested on:

3.11, 3.12, 3.13, 3.14, 3.15, 3.16, CPython main branch

Operating systems tested on:

Linux

Output from running 'python -VV' on the command line:

Python 3.15.2 (main, Nov 25 2026, 20:06:37) [Clang 18.1.3 (1ubuntu1)]

Activity

  1. added
    type-crash
    on Nov 26, 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

    type-crash

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions