Skip to content

UAF in GC visit_generation() #160663

Open
Open

Description

@johng

Bug report

Similar to #112564 we call GC_NEXT(gc) which is vulnerable to UAF in

cpython/Python/gc.c

Lines 2165 to 2179 in 036d309

visit_generation(gcvisitobjects_t callback, void *arg, struct gc_generation *gen)
{
PyGC_Head *gc_list, *gc;
gc_list = &gen->head;
for (gc = GC_NEXT(gc_list); gc != gc_list; gc = GC_NEXT(gc)) {
PyObject *op = FROM_GC(gc);
Py_INCREF(op);
int res = callback(op, arg);
Py_DECREF(op);
if (!res) {
return -1;
}
}
return 0;
}

Fix could be similar to proposal in #160662

Reproduction, similar to the above bug we are looping through each entity but rely on the entity being alive when calling NEXT in the entity loop

#include <Python.h>

static PyObject *victim;            /* the only reference to the victim */

static int
drop_current(PyObject *op, void *arg)
{
    if (op == victim) {
        Py_CLEAR(victim);           /* the visitor's +1 is now the last ref */
    }
    return 1;
}

static PyObject *
run(PyObject *module, PyObject *unused)
{
    victim = PySet_New(NULL);       /* GC-tracked, and sets have no freelist */
    if (victim == NULL) {
        return NULL;
    }
    PyUnstable_GC_VisitObjects(drop_current, NULL);     /* segfaults */
    Py_RETURN_NONE;
}

static PyMethodDef methods[] = {
    {"run", run, METH_NOARGS, NULL},
    {NULL, NULL, 0, NULL},
};

static struct PyModuleDef module = {
    PyModuleDef_HEAD_INIT, "visitmin", NULL, -1, methods,
};

PyMODINIT_FUNC
PyInit_visitmin(void)
{
    return PyModule_Create(&module);
}

import visitmin
visitmin.run()
print("no crash")

CPython versions tested on:

CPython main branch

Operating systems tested on:

macOS

Linked PRs

Activity

  1. added
    type-bugAn unexpected behavior, bug, or error
    on Oct 25, 2026
  2. added
    interpreter-core(Objects, Python, Grammar, and Parser dirs)
    type-crashA hard crash of the interpreter, possibly with a core dump
    on Oct 25, 2026
  3. sergey-miryanov commented on Oct 25, 2026

    @sergey-miryanov
    Contributor

    @johng Would you like to open a PR?

  4. nascheme commented on Oct 30, 2026

    @nascheme
    Member

    @encukou FYI we likely need to improve the documentation for PyUnstable_GC_VisitObjects and specifically what the callback function is allowed to do. This feature was added in GH-102013. Making the GC slower and more complex to support user provided visit callbacks is not what we want.

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

    interpreter-core(Objects, Python, Grammar, and Parser dirs)type-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