closes bpo-39510: Fix use-after-free in BufferedReader.readinto() (GH-18295)

When called on a closed object, readinto() segfaults on account
of a write to a freed buffer:

    ==220553== Process terminating with default action of signal 11 (SIGSEGV): dumping core
    ==220553==  Access not within mapped region at address 0x2A
    ==220553==    at 0x48408A0: memmove (vg_replace_strmem.c:1272)
    ==220553==    by 0x58DB0C: _buffered_readinto_generic (bufferedio.c:972)
    ==220553==    by 0x58DCBA: _io__Buffered_readinto_impl (bufferedio.c:1053)
    ==220553==    by 0x58DCBA: _io__Buffered_readinto (bufferedio.c.h:253)

Reproducer:

    reader = open ("/dev/zero", "rb")
    _void  = reader.read (42)
    reader.close ()
    reader.readinto (bytearray (42)) ### BANG!

The problem exists since 2012 when commit dc469454ec added code
to free the read buffer on close().

Signed-off-by: Philipp Gesang <philipp.gesang@intra2net.com>
This commit is contained in:
Philipp Gesang 2020-02-04 22:25:16 +01:00 committed by GitHub
parent 9538bc9185
commit cb1c0746f2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 7 additions and 0 deletions

View File

@ -737,6 +737,11 @@ class IOTest(unittest.TestCase):
file.seek(0)
file.close()
self.assertRaises(ValueError, file.read)
with self.open(support.TESTFN, "rb") as f:
file = self.open(f.fileno(), "rb", closefd=False)
self.assertEqual(file.read()[:3], b"egg")
file.close()
self.assertRaises(ValueError, file.readinto, bytearray(1))
def test_no_closefd_with_filename(self):
# can't use closefd in combination with a file name

View File

@ -0,0 +1 @@
Fix segfault in ``readinto()`` method on closed BufferedReader.

View File

@ -965,6 +965,7 @@ _buffered_readinto_generic(buffered *self, Py_buffer *buffer, char readinto1)
PyObject *res = NULL;
CHECK_INITIALIZED(self)
CHECK_CLOSED(self, "readinto of closed file")
n = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t);
if (n > 0) {