]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-134100: Fix use-after-free in `PyImport_ImportModuleLevelObject` (#134117)
authorNico-Posada <102486290+Nico-Posada@users.noreply.github.com>
Sun, 18 May 2025 07:11:38 +0000 (03:11 -0400)
committerGitHub <noreply@github.com>
Sun, 18 May 2025 07:11:38 +0000 (12:41 +0530)
Lib/test/test_importlib/import_/test_relative_imports.py
Misc/NEWS.d/next/Core_and_Builtins/2025-05-16-17-25-52.gh-issue-134100.5-FbLK.rst [new file with mode: 0644]
Python/import.c

index e535d1197631484612335f26c29c3b8f98afae7f..1549cbe96ce2d1ae5d3547cef4bf3b0f883304e1 100644 (file)
@@ -223,6 +223,21 @@ class RelativeImports:
             self.__import__('sys', {'__package__': '', '__spec__': None},
                             level=1)
 
+    def test_malicious_relative_import(self):
+        # https://github.com/python/cpython/issues/134100
+        # Test to make sure UAF bug with error msg doesn't come back to life
+        import sys
+        loooong = "".ljust(0x23000, "b")
+        name = f"a.{loooong}.c"
+
+        with util.uncache(name):
+            sys.modules[name] = {}
+            with self.assertRaisesRegex(
+                KeyError,
+                r"'a\.b+' not in sys\.modules as expected"
+            ):
+                __import__(f"{loooong}.c", {"__package__": "a"}, level=1)
+
 
 (Frozen_RelativeImports,
  Source_RelativeImports
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2025-05-16-17-25-52.gh-issue-134100.5-FbLK.rst b/Misc/NEWS.d/next/Core_and_Builtins/2025-05-16-17-25-52.gh-issue-134100.5-FbLK.rst
new file mode 100644 (file)
index 0000000..d672347
--- /dev/null
@@ -0,0 +1,2 @@
+Fix a use-after-free bug that occurs when an imported module isn't
+in :data:`sys.modules` after its initial import. Patch by Nico-Posada.
index 9dec0f488a3b905e4517652d095d6045620d5f2e..e7be1b90751a6c0f7dba00a44874126fc413017d 100644 (file)
@@ -3854,15 +3854,17 @@ PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
                 }
 
                 final_mod = import_get_module(tstate, to_return);
-                Py_DECREF(to_return);
                 if (final_mod == NULL) {
                     if (!_PyErr_Occurred(tstate)) {
                         _PyErr_Format(tstate, PyExc_KeyError,
                                       "%R not in sys.modules as expected",
                                       to_return);
                     }
+                    Py_DECREF(to_return);
                     goto error;
                 }
+
+                Py_DECREF(to_return);
             }
         }
         else {