https://github.com/python/cpython/commit/b8845369aa76a6b2d4f147243d8451ce00abc661
commit: b8845369aa76a6b2d4f147243d8451ce00abc661
branch: 3.12
author: Miss Islington (bot) <[email protected]>
committer: sobolevn <[email protected]>
date: 2024-06-11T07:22:59Z
summary:

[3.12] gh-120298: Fix use-after-free in `list_richcompare_impl` (GH-120303) 
(#120339)

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

Co-authored-by: Nikita Sobolev <[email protected]>
Co-authored-by: Serhiy Storchaka <[email protected]>

files:
A Misc/NEWS.d/next/Core and 
Builtins/2024-06-10-10-42-48.gh-issue-120298.napREA.rst
M Lib/test/test_list.py
M Objects/listobject.c

diff --git a/Lib/test/test_list.py b/Lib/test/test_list.py
index 2969c6e2f98a23..4207f2b364542c 100644
--- a/Lib/test/test_list.py
+++ b/Lib/test/test_list.py
@@ -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
diff --git a/Misc/NEWS.d/next/Core and 
Builtins/2024-06-10-10-42-48.gh-issue-120298.napREA.rst b/Misc/NEWS.d/next/Core 
and Builtins/2024-06-10-10-42-48.gh-issue-120298.napREA.rst
new file mode 100644
index 00000000000000..531d39517ac423
--- /dev/null
+++ b/Misc/NEWS.d/next/Core and 
Builtins/2024-06-10-10-42-48.gh-issue-120298.napREA.rst 
@@ -0,0 +1,2 @@
+Fix use-after free in ``list_richcompare_impl`` which can be invoked via
+some specificly tailored evil input.
diff --git a/Objects/listobject.c b/Objects/listobject.c
index f59abe2e644f14..ee724dbe1460f0 100644
--- a/Objects/listobject.c
+++ b/Objects/listobject.c
@@ -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]

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-checkins.python.org/
Member address: [email protected]

Reply via email to