Skip to content

Use-after-free in {Attribute,Name,Import}Error suggestion generation #157947

Description

@stratakis

Crash report

What happened?

Summary

This is a Use-after-free (CWE-416), interpreter crash. Only reachable by running crafted Python, which per the Python security policy is not a security boundary, so opening it as a regular bug per the request of the Python Security team.

The "Did you mean: ...?" suggestion helpers in Python/suggestions.c hold borrowed references to exception fields across PyObject_Dir(), which can run arbitrary Python. Re-entrant code that reassigns those fields frees them mid-use, causing a use-after-free during exception display. Affects 3.10-3.12.

Details

_PyErr_PrintEx() sets sys.last_value to the live exception before display, which reaches get_suggestions_for_attribute_error():

    PyObject *name = exc->name;         // borrowed
    PyObject *dir = PyObject_Dir(obj);  // runs obj.__dir__() -> arbitrary Python
    calculate_suggestions(dir, name);   // uses stale `name`

AttributeError.name is a T_OBJECT member whose setter decrefs the old value, so code in obj.__dir__() can reach the exception via sys.last_value, do exc.name = ..., and free the borrowed string before calculate_suggestions() dereferences it. Same pattern in the NameError and ImportError paths.

PoC

      import sys
      def fresh_name():
          return ("X" * (4 * 1024 * 1024)) + "!"   # mmap'd -> munmap on free
      class Evil:
          def __dir__(self):
              exc = getattr(sys, "last_value", None)
              if isinstance(exc, AttributeError):
                  exc.name = "replaced"; exc.obj = None
              return ["x"] 
      raise AttributeError("boom", name=fresh_name(), obj=Evil()

python3.12 repro.py -> SIGSEGV in PyUnicode_AsUTF8AndSize <- calculate_suggestions.

Fixed incidentally in 3.13 (#110721 which moved display to the traceback module). Only 3.10-3.12 need the strong-reference fix.

CPython versions tested on:

3.10, 3.11, 3.12

Operating systems tested on:

Linux

Output from running 'python -VV' on the command line:

No response

Linked PRs

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.10only security fixes3.11only security fixes3.12only security fixesinterpreter-core(Objects, Python, Grammar, and Parser dirs)pendingThe issue will be closed if no feedback is providedtype-crashA hard crash of the interpreter, possibly with a core dump

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions