Skip to content

PyMemoryView_FromBuffer discards owner reference from Py_buffer #148493

@alex

Description

@alex

Bug report

Bug description:

PyObject *
PyMemoryView_FromBuffer(const Py_buffer *info)
{
_PyManagedBufferObject *mbuf;
PyObject *mv;
if (info->buf == NULL) {
PyErr_SetString(PyExc_ValueError,
"PyMemoryView_FromBuffer(): info->buf must not be NULL");
return NULL;
}
mbuf = mbuf_alloc();
if (mbuf == NULL)
return NULL;
/* info->obj is either NULL or a borrowed reference. This reference
should not be decremented in PyBuffer_Release(). */
mbuf->master = *info;
mbuf->master.obj = NULL;

This means that if you use PyMemoryView_FromBuffer with a buffer that requires an owner to be kept alive, you get a UAF hazard here.

This is not mentioned in the documentation: https://docs.python.org/3/c-api/memoryview.html#c.PyMemoryView_FromBuffer

An extremely cursory didn't find any vulnerable callers within CPython itself, however this was discovered in the process of implementing PyO3/pyo3#5937 where it definitely would have been an issue.

It seems like there's two possible choices here:

  • Change this to keep owner around -- potentially breaks existing callers?
  • Document this, and introduce a new API with clearer semantics here.

CPython versions tested on:

CPython main branch

Operating systems tested on:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)topic-C-APItype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions