Skip to content

Commit 8d51ed6

Browse files
[3.14] gh-134100: Fix use-after-free in PyImport_ImportModuleLevelObject (GH-134117) (#134171)
gh-134100: Fix use-after-free in `PyImport_ImportModuleLevelObject` (GH-134117) (cherry picked from commit 4e9005d) Co-authored-by: Nico-Posada <[email protected]>
1 parent bf39dec commit 8d51ed6

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

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
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a use-after-free bug that occurs when an imported module isn't
2+
in :data:`sys.modules` after its initial import. Patch by Nico-Posada.

Python/import.c

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

38543854
final_mod = import_get_module(tstate, to_return);
3855-
Py_DECREF(to_return);
38563855
if (final_mod == NULL) {
38573856
if (!_PyErr_Occurred(tstate)) {
38583857
_PyErr_Format(tstate, PyExc_KeyError,
38593858
"%R not in sys.modules as expected",
38603859
to_return);
38613860
}
3861+
Py_DECREF(to_return);
38623862
goto error;
38633863
}
3864+
3865+
Py_DECREF(to_return);
38643866
}
38653867
}
38663868
else {

0 commit comments

Comments
 (0)