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
- Add runtime validation in
PyBuffer_ToContiguous()
- Add assertion in
buffer_to_contiguous() for consistency
- Add test case in
test_memoryview.py
- 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
Proposal:
Summary
The
PyBuffer_ToContiguous()function inObjects/memoryobject.cdoes not validate thendimparameter before using it in memory allocation calculations, which could theoretically lead to integer overflow.Current Behavior
The allocation calculation
3 * src->ndim * sizeof(Py_ssize_t)does not validatendimbefore use.Proposed Solution
Add validation to ensure
ndimis within the valid range (0 toPyBUF_MAX_NDIM, which is 64):Impact Assessment
ndim > ~3.8×10^17)PyBUF_MAX_NDIMgetbufferprocClassification
This is a defense-in-depth hardening improvement, not a security vulnerability fix. No CVE is warranted.
Proposed Changes
PyBuffer_ToContiguous()buffer_to_contiguous()for consistencytest_memoryview.pyBenefits
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