From f794b143d32c30f4a910ff19bded3e62c20313e1 Mon Sep 17 00:00:00 2001 From: Mark Dickinson Date: Sat, 13 Apr 2013 15:19:05 +0100 Subject: Issue #16447: Fix potential segfault when setting __name__ on a class. --- Lib/test/test_descr.py | 14 ++++++++++++++ Misc/NEWS | 3 +++ Objects/typeobject.c | 6 +++++- 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/Lib/test/test_descr.py b/Lib/test/test_descr.py index bfb3552..07664ac 100644 --- a/Lib/test/test_descr.py +++ b/Lib/test/test_descr.py @@ -4136,6 +4136,20 @@ order (MRO) for bases """ C.__name__ = 'D.E' self.assertEqual((C.__module__, C.__name__), (mod, 'D.E')) + def test_evil_type_name(self): + # A badly placed Py_DECREF in type_set_name led to arbitrary code + # execution while the type structure was not in a sane state, and a + # possible segmentation fault as a result. See bug #16447. + class Nasty(str): + def __del__(self): + C.__name__ = "other" + + class C(object): + pass + + C.__name__ = Nasty("abc") + C.__name__ = "normal" + def test_subclass_right_op(self): # Testing correct dispatch of subclass overloading __r__... diff --git a/Misc/NEWS b/Misc/NEWS index ee5393c..cb0dfc8 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -17,6 +17,9 @@ Build Core and Builtins ----------------- +- Issue #16447: Fixed potential segmentation fault when setting __name__ on a + class. + - Issue #17610: Don't rely on non-standard behavior of the C qsort() function. Library diff --git a/Objects/typeobject.c b/Objects/typeobject.c index 6c88f53..be04c9e 100644 --- a/Objects/typeobject.c +++ b/Objects/typeobject.c @@ -225,6 +225,7 @@ static int type_set_name(PyTypeObject *type, PyObject *value, void *context) { PyHeapTypeObject* et; + PyObject *tmp; if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { PyErr_Format(PyExc_TypeError, @@ -253,10 +254,13 @@ type_set_name(PyTypeObject *type, PyObject *value, void *context) Py_INCREF(value); - Py_DECREF(et->ht_name); + /* Wait until et is a sane state before Py_DECREF'ing the old et->ht_name + value. (Bug #16447.) */ + tmp = et->ht_name; et->ht_name = value; type->tp_name = PyString_AS_STRING(value); + Py_DECREF(tmp); return 0; } -- cgit v0.12