Skip to content

Heap buffer overflow in _textiowrapper_writeflush() after a re-entrant TextIOWrapper.__init__() #162659

Backlog

Description

@xuziqiang98

Crash report

io.TextIOWrapper.__init__() can be called again on an existing object. It clears the old pending_bytes list with Py_CLEAR() and resets pending_bytes_count to 0 only after that.

Deallocating the list can run arbitrary Python code: pending_bytes holds references to the objects passed to write() (in the reproducer below the str subclass instance itself), so a __del__ runs here. If that code calls write() on the same wrapper, the nested write stores new data and bumps pending_bytes_count. The outer __init__() then resets the count to 0 while the new data stays. From then on pending_bytes and pending_bytes_count disagree, and the next flush() sizes its buffer from the count while copying the real lengths of the list items.

Reproducer

import io


class E(str):
    def __del__(self):
        # Runs from Py_CLEAR(self->pending_bytes) inside the outer __init__().
        # The nested write() stores 1000 bytes and bumps pending_bytes_count;
        # the outer __init__() then resets pending_bytes_count to 0.
        self.w.__init__(io.BytesIO(), encoding="ascii")
        self.w.write("A" * 1000)


w = io.TextIOWrapper(io.BytesIO(), encoding="ascii")
E.w = w
e = E("A" * 1000)
w.write(e)       # pending_bytes = e,        pending_bytes_count = 1000
w.write("x")     # pending_bytes = [e, "x"], pending_bytes_count = 1001
del e            # only the pending list keeps e alive

w.__init__(io.BytesIO(), encoding="ascii")   # runs E.__del__(), then zeroes the count

w.write("B")     # pending_bytes = [<1000 bytes>, "B"], pending_bytes_count = 1
w.flush()        # buffer sized for 1 byte, 1000 bytes memcpy'ed into it

print("no crash")

Output

3.15.2, built from the official tarball with --with-address-sanitizer:

ERROR: AddressSanitizer: heap-buffer-overflow
WRITE of size 1000 at 0x50400005e7b2 thread T0
    #0 __asan_memcpy
    #1 _textiowrapper_writeflush Modules/_io/textio.c:1702:13
    #2 _io_TextIOWrapper_flush_impl Modules/_io/textio.c:3224:9
    #3 _io_TextIOWrapper_flush Modules/_io/clinic/textio.c.h:1156:20
    ...
0x50400005e7b2 is located 0 bytes after 34-byte region [0x50400005e790,0x50400005e7b2)
allocated by thread T0 here:
    #1 _PyBytes_FromSize Objects/bytesobject.c:111:31
    #2 PyBytes_FromStringAndSize Objects/bytesobject.c:141:27
    #3 _textiowrapper_writeflush Modules/_io/textio.c:1678:13
    #4 _io_TextIOWrapper_flush_impl Modules/_io/textio.c:3224:9

The 34-byte region is the 1-byte bytes object allocated for pending_bytes_count == 1.

ASan reports the same overflow 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.

Without a sanitizer the script segfaults on some builds (3.12.3: 3 of 3 runs, 3.13.5: 5 of 5) and exits 0 on others (3.15.0: 1 of 5 segfaulted). The copy happens in every case.

On 3.16/main the flush buffer is a PyBytesWriter. With a stale string of 256 to 279 bytes the copy stays inside the writer's own 280-byte allocation and overwrites the fields that follow its buffer, so ASan reports no overflow; PyBytesWriter_Finish() then dereferences the garbage and the process dies with SIGSEGV (seen on 3.16.0a2 with a 272-byte stale string, in byteswriter_finish_with_size() called from _textiowrapper_writeflush()).

Analysis

Modules/_io/textio.c, _io_TextIOWrapper___init___impl() (main, 4b66b87):

    Py_CLEAR(self->decoded_chars);
    Py_CLEAR(self->pending_bytes);            /* line 1237: may run Python code */
    Py_CLEAR(self->snapshot);
    Py_CLEAR(self->errors);
    Py_CLEAR(self->raw);
    self->decoded_chars_used = 0;
    self->pending_bytes_count = 0;            /* line 1242: too late */
    self->encodefunc = NULL;

_io_TextIOWrapper_write_impl() finds a non-NULL pending_bytes that is not a list, builds the list [<stale 1000 bytes>, "B"] and adds only the length of "B" to the count. _textiowrapper_writeflush() then allocates from the count (PyBytesWriter_Create(self->pending_bytes_count) on main, PyBytes_FromStringAndSize(NULL, self->pending_bytes_count) up to 3.15) and memcpy()s every list item into that buffer.

Possible fix

Reset the count before the list is deallocated, so that the two fields agree again before any Python code can run:

@@ -1220,12 +1220,15 @@
     Py_CLEAR(self->decoder);
     Py_CLEAR(self->readnl);
     Py_CLEAR(self->decoded_chars);
+    /* Reset the count before the list is deallocated: deallocating it can
+       run arbitrary Python code (e.g. a str subclass __del__) that writes
+       to self again. */
+    self->pending_bytes_count = 0;
     Py_CLEAR(self->pending_bytes);
     Py_CLEAR(self->snapshot);
     Py_CLEAR(self->errors);
     Py_CLEAR(self->raw);
     self->decoded_chars_used = 0;
-    self->pending_bytes_count = 0;
     self->encodefunc = NULL;
     self->b2cratio = 0.0;
 

I tested this on 3.15.2: the reproducer no longer triggers ASan (5 of 5 runs) and test_io passes (with ASan's allocator_may_return_null=1; without it test_io.test_bufferedio aborts on an unrelated huge allocation, on the unpatched build as well). The other scalar fields that are reset after the Py_CLEAR() calls (decoded_chars_used, encodefunc) may deserve the same treatment; I have not checked whether they can be misused this way.

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
  2. added
    extension-modules
    3.14
    3.15
    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

    3.143.15extension-modulestopic-IOtype-crash

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions