Skip to content

Commit

Permalink
[3.12] gh-120298: Fix use-after-free in list_richcompare_impl (GH-1…
Browse files Browse the repository at this point in the history
…20303) (#120339)

gh-120298: Fix use-after-free in `list_richcompare_impl` (GH-120303)
(cherry picked from commit 141baba)

Co-authored-by: Nikita Sobolev <[email protected]>
Co-authored-by: Serhiy Storchaka <[email protected]>
  • Loading branch information
3 people authored Jun 11, 2024
1 parent f648192 commit b884536
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
11 changes: 11 additions & 0 deletions Lib/test/test_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,17 @@ def __eq__(self, other):
list4 = [1]
self.assertFalse(list3 == list4)

def test_lt_operator_modifying_operand(self):
# See gh-120298
class evil:
def __lt__(self, other):
other.clear()
return NotImplemented

a = [[evil()]]
with self.assertRaises(TypeError):
a[0] < a

@cpython_only
def test_preallocation(self):
iterable = [0] * 10
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix use-after free in ``list_richcompare_impl`` which can be invoked via
some specificly tailored evil input.
9 changes: 8 additions & 1 deletion Objects/listobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -2759,7 +2759,14 @@ list_richcompare(PyObject *v, PyObject *w, int op)
}

/* Compare the final item again using the proper operator */
return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
PyObject *vitem = vl->ob_item[i];
PyObject *witem = wl->ob_item[i];
Py_INCREF(vitem);
Py_INCREF(witem);
PyObject *result = PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
Py_DECREF(vitem);
Py_DECREF(witem);
return result;
}

/*[clinic input]
Expand Down

0 comments on commit b884536

Please sign in to comment.