Skip to content

Add ndim validation to PyBuffer_ToContiguous for defense-in-depth #146525

@l3tchupkt

Description

@l3tchupkt

Proposal:

Summary

The PyBuffer_ToContiguous() function in Objects/memoryobject.c does not validate the ndim parameter before using it in memory allocation calculations, which could theoretically lead to integer overflow.

Current Behavior

// Objects/memoryobject.c, line ~1069
fb = PyMem_Malloc(sizeof *fb + 3 * src->ndim * (sizeof *fb->array));

The allocation calculation 3 * src->ndim * sizeof(Py_ssize_t) does not validate ndim before use.

Proposed Solution

Add validation to ensure ndim is within the valid range (0 to PyBUF_MAX_NDIM, which is 64):

if (src->ndim < 0 || src->ndim > PyBUF_MAX_NDIM) {
    PyErr_Format(PyExc_ValueError,
                 "ndim out of valid range (got %d, expected 0-%d)",
                 src->ndim, PyBUF_MAX_NDIM);
    return -1;
}

Impact Assessment

  • Severity: Low (hardening, not an active vulnerability)
  • Exploitability: Not practically exploitable (would require ndim > ~3.8×10^17)
  • Current Protection: Python-level code already enforces PyBUF_MAX_NDIM
  • Attack Vector: Would require a malicious C extension with custom getbufferproc

Classification

This is a defense-in-depth hardening improvement, not a security vulnerability fix. No CVE is warranted.

Proposed Changes

  1. Add runtime validation in PyBuffer_ToContiguous()
  2. Add assertion in buffer_to_contiguous() for consistency
  3. Add test case in test_memoryview.py
  4. Add NEWS entry

Benefits

  • Explicit validation makes assumptions clear
  • Prevents potential misuse by malformed C extensions
  • Improves code quality and robustness
  • Aligns C-level checks with Python-level enforcement

Linked Components: C API, Buffer Protocol
Type: Enhancement (Hardening)
Affected Versions: All versions (hardening improvement)

Has this already been discussed elsewhere?

No response given

Links to previous discussion of this feature:

No response

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)pendingThe issue will be closed if no feedback is providedtopic-C-APItype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions