Skip to content

Commit df6385e

Browse files
miss-islingtonNico-Posada
authored andcommitted
[3.13] pythongh-134100: Fix use-after-free in PyImport_ImportModuleLevelObject (pythonGH-134117) (python#134172)
pythongh-134100: Fix use-after-free in `PyImport_ImportModuleLevelObject` (pythonGH-134117) (cherry picked from commit 4e9005d) Co-authored-by: Nico-Posada <102486290+Nico-Posada@users.noreply.github.com> Signed-off-by: Michał Górny <mgorny@gentoo.org>
1 parent 4152589 commit df6385e

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

Lib/test/test_importlib/import_/test_relative_imports.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,21 @@ def test_relative_import_no_package_exists_absolute(self):
223223
self.__import__('sys', {'__package__': '', '__spec__': None},
224224
level=1)
225225

226+
def test_malicious_relative_import(self):
227+
# https://github.com/python/cpython/issues/134100
228+
# Test to make sure UAF bug with error msg doesn't come back to life
229+
import sys
230+
loooong = "".ljust(0x23000, "b")
231+
name = f"a.{loooong}.c"
232+
233+
with util.uncache(name):
234+
sys.modules[name] = {}
235+
with self.assertRaisesRegex(
236+
KeyError,
237+
r"'a\.b+' not in sys\.modules as expected"
238+
):
239+
__import__(f"{loooong}.c", {"__package__": "a"}, level=1)
240+
226241

227242
(Frozen_RelativeImports,
228243
Source_RelativeImports

Python/import.c

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1922,15 +1922,17 @@ PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
19221922
}
19231923

19241924
final_mod = import_get_module(tstate, to_return);
1925-
Py_DECREF(to_return);
19261925
if (final_mod == NULL) {
19271926
if (!_PyErr_Occurred(tstate)) {
19281927
_PyErr_Format(tstate, PyExc_KeyError,
19291928
"%R not in sys.modules as expected",
19301929
to_return);
19311930
}
1931+
Py_DECREF(to_return);
19321932
goto error;
19331933
}
1934+
1935+
Py_DECREF(to_return);
19341936
}
19351937
}
19361938
else {

0 commit comments

Comments
 (0)