]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
GH-97592: Fix crash in C remove_done_callback due to evil code (#97660)
authorGuido van Rossum <guido@python.org>
Fri, 30 Sep 2022 19:57:09 +0000 (12:57 -0700)
committerGitHub <noreply@github.com>
Fri, 30 Sep 2022 19:57:09 +0000 (12:57 -0700)
Evil code could cause fut_callbacks to be cleared when PyObject_RichCompareBool is called.

Lib/test/test_asyncio/test_futures.py
Misc/NEWS.d/next/Library/2022-09-29-23-22-24.gh-issue-97592.tpJg_J.rst [new file with mode: 0644]
Modules/_asynciomodule.c

index 11d4273930804f66ab5cdec039dc1a8cc9b816ca..3dc6b658cfae8d19b2fcfcf415b953d6b1d7d3b9 100644 (file)
@@ -837,6 +837,21 @@ class BaseFutureDoneCallbackTests():
 
         fut.remove_done_callback(evil())
 
+    def test_remove_done_callbacks_list_clear(self):
+        # see https://github.com/python/cpython/issues/97592 for details
+
+        fut = self._new_future()
+        fut.add_done_callback(str)
+
+        for _ in range(63):
+            fut.add_done_callback(id)
+
+        class evil:
+            def __eq__(self, other):
+                fut.remove_done_callback(other)
+
+        fut.remove_done_callback(evil())
+
     def test_schedule_callbacks_list_mutation_1(self):
         # see http://bugs.python.org/issue28963 for details
 
diff --git a/Misc/NEWS.d/next/Library/2022-09-29-23-22-24.gh-issue-97592.tpJg_J.rst b/Misc/NEWS.d/next/Library/2022-09-29-23-22-24.gh-issue-97592.tpJg_J.rst
new file mode 100644 (file)
index 0000000..aa245cf
--- /dev/null
@@ -0,0 +1 @@
+Avoid a crash in the C version of :meth:`asyncio.Future.remove_done_callback` when an evil argument is passed.
index 5a5881b873e245c9e3aa3739fca3557ff697c0d6..909171150bdd363dd718ba58ae630f9f9735d89d 100644 (file)
@@ -1052,7 +1052,11 @@ _asyncio_Future_remove_done_callback(FutureObj *self, PyObject *fn)
         return NULL;
     }
 
-    for (i = 0; i < PyList_GET_SIZE(self->fut_callbacks); i++) {
+    // Beware: PyObject_RichCompareBool below may change fut_callbacks.
+    // See GH-97592.
+    for (i = 0;
+         self->fut_callbacks != NULL && i < PyList_GET_SIZE(self->fut_callbacks);
+         i++) {
         int ret;
         PyObject *item = PyList_GET_ITEM(self->fut_callbacks, i);
         Py_INCREF(item);
@@ -1071,7 +1075,8 @@ _asyncio_Future_remove_done_callback(FutureObj *self, PyObject *fn)
         }
     }
 
-    if (j == 0) {
+    // Note: fut_callbacks may have been cleared.
+    if (j == 0 || self->fut_callbacks == NULL) {
         Py_CLEAR(self->fut_callbacks);
         Py_DECREF(newlist);
         return PyLong_FromSsize_t(len + cleared_callback0);