[New-bugs-announce] [issue24044] NULL pointer dereference in listsort() with key function

Benjamin Peterson report at bugs.python.org
Thu Apr 23 23:03:08 CEST 2015

New submission from Benjamin Peterson:

Found by Christian Heimes:

Coverity has found a flaw in Objects/listobject.c:listsort() that
eventually leads to a NULL pointer dereference. Because NULL pointer
dereferences can lead to exploits or DoS vulnerabilities I'm reporting
the error on PSRT first. The error is on a code path that can be
triggered by a remote attacker, although not that easily. All Python 3
versions are affected, Python 2.7 looks save.

The problematic code line is
. The code fails to restore self->ob_item to saved_ob_item when
PyMem_MALLOC() fails. Subsequent access to the same list object will
dereference self->ob_item (which is still NULL) and cause a segfault.

A remote attack might be able to trigger the segfault with a large
data set. All it takes is an application that sorts this large data
set with list.sort() and a custom key function. When Python runs out
of memory just in the right spot ... CRASH.

Additionally there is another bug, too. list.sort() doesn't set an
exception when PyMem_MALLOC() fails. A fix for both issues is simple
and straight forward:

diff -r bc1a178b3bc8 Objects/listobject.c
- --- a/Objects/listobject.c      Sat Apr 18 05:54:02 2015 +0200
+++ b/Objects/listobject.c      Sat Apr 18 06:29:02 2015 +0200
@@ -1961,8 +1961,10 @@
             keys = &ms.temparray[saved_ob_size+1];
         else {
             keys = PyMem_MALLOC(sizeof(PyObject *) * saved_ob_size);
- -            if (keys == NULL)
- -                return NULL;
+            if (keys == NULL) {
+                PyErr_NoMemory();
+                goto keyfunc_fail;
+            }

         for (i = 0; i < saved_ob_size ; i++) {

components: Interpreter Core
messages: 241889
nosy: benjamin.peterson, christian.heimes
priority: high
severity: normal
status: open
title: NULL pointer dereference in listsort() with key function
type: crash
versions: Python 2.7, Python 3.2, Python 3.3, Python 3.4, Python 3.5, Python 3.6

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list