-
-
Notifications
You must be signed in to change notification settings - Fork 34.3k
Open
Labels
interpreter-core(Objects, Python, Grammar, and Parser dirs)(Objects, Python, Grammar, and Parser dirs)pendingThe issue will be closed if no feedback is providedThe issue will be closed if no feedback is providedtopic-C-APItype-featureA feature request or enhancementA feature request or enhancement
Description
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
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
interpreter-core(Objects, Python, Grammar, and Parser dirs)(Objects, Python, Grammar, and Parser dirs)pendingThe issue will be closed if no feedback is providedThe issue will be closed if no feedback is providedtopic-C-APItype-featureA feature request or enhancementA feature request or enhancement