From: Benjamin Johnson Date: Wed, 17 Dec 2025 15:09:57 +0000 (-0800) Subject: gh-112127: Fix possible use-after-free in atexit.unregister() (GH-114092) X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=2b466c47c333106dc9522ab77898e6972e25a2c6;p=thirdparty%2FPython%2Fcpython.git gh-112127: Fix possible use-after-free in atexit.unregister() (GH-114092) Co-authored-by: Serhiy Storchaka --- diff --git a/Lib/test/_test_atexit.py b/Lib/test/_test_atexit.py index f618c1fcbca5..490b0686a0c1 100644 --- a/Lib/test/_test_atexit.py +++ b/Lib/test/_test_atexit.py @@ -135,6 +135,19 @@ class GeneralTest(unittest.TestCase): finally: atexit.unregister(func) + def test_eq_unregister_clear(self): + # Issue #112127: callback's __eq__ may call unregister or _clear + class Evil: + def __eq__(self, other): + action(other) + return NotImplemented + + for action in atexit.unregister, lambda o: atexit._clear(): + with self.subTest(action=action): + atexit.register(lambda: None) + atexit.unregister(Evil()) + atexit._clear() + if __name__ == "__main__": unittest.main() diff --git a/Misc/ACKS b/Misc/ACKS index e3927ff0b336..a14089a39cce 100644 --- a/Misc/ACKS +++ b/Misc/ACKS @@ -908,6 +908,7 @@ Jim Jewett Pedro Diaz Jimenez Orjan Johansen Fredrik Johansson +Benjamin Johnson Benjamin K. Johnson Gregory K. Johnson Kent Johnson diff --git a/Misc/NEWS.d/next/Library/2025-12-17-14-41-09.gh-issue-112127.13OHQk.rst b/Misc/NEWS.d/next/Library/2025-12-17-14-41-09.gh-issue-112127.13OHQk.rst new file mode 100644 index 000000000000..c983683ebd55 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-12-17-14-41-09.gh-issue-112127.13OHQk.rst @@ -0,0 +1,2 @@ +Fix possible use-after-free in :func:`atexit.unregister` when the callback +is unregistered during comparison. diff --git a/Modules/atexitmodule.c b/Modules/atexitmodule.c index 4536b03fbc4d..f81f0b572479 100644 --- a/Modules/atexitmodule.c +++ b/Modules/atexitmodule.c @@ -257,10 +257,11 @@ static int atexit_unregister_locked(PyObject *callbacks, PyObject *func) { for (Py_ssize_t i = 0; i < PyList_GET_SIZE(callbacks); ++i) { - PyObject *tuple = PyList_GET_ITEM(callbacks, i); + PyObject *tuple = Py_NewRef(PyList_GET_ITEM(callbacks, i)); assert(PyTuple_CheckExact(tuple)); PyObject *to_compare = PyTuple_GET_ITEM(tuple, 0); int cmp = PyObject_RichCompareBool(func, to_compare, Py_EQ); + Py_DECREF(tuple); if (cmp < 0) { return -1;