Open
Description
Bug report
Bug description:
Description:
The Balloc
function in Python/dtoa.c
contains an integer overflow vulnerability when calculating memory allocation sizes. This occurs when processing large values of x
(where x = 1 << k
), causing an insufficient buffer allocation that can lead to heap corruption.
Vulnerable Code:
// Original unsafe calculation
len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
/ sizeof(double);
rv = (Bigint*)MALLOC(len * sizeof(double));
Proof of Concept:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <stdint.h>
// Simulate vulnerable allocation calculation
void vulnerable_allocation(int k) {
int x = 1 << k;
size_t len = (sizeof(double) + (x-1)*sizeof(unsigned long) +
sizeof(double) - 1) / sizeof(double);
size_t actual_required = sizeof(double) + (x-1)*sizeof(unsigned long);
size_t allocated = len * sizeof(double);
printf("k=%d, x=%d\n", k, x);
printf("Calculated len: %zu\n", len);
printf("Allocated size: %zu bytes\n", allocated);
printf("Actual required: %zu bytes\n", actual_required);
if (allocated < actual_required) {
printf("VULNERABLE: Under-allocation by %zu bytes\n",
actual_required - allocated);
} else {
printf("Safe allocation\n");
}
printf("---------------------------------\n");
}
int main() {
// Test different k values
vulnerable_allocation(10); // Safe (small)
vulnerable_allocation(20); // Safe (medium)
vulnerable_allocation(28); // Vulnerable on 32-bit systems
vulnerable_allocation(30); // Highly vulnerable
return 0;
}
Compilation and Execution:
# Compile for 32-bit system
gcc -m32 -O0 poc.c -o poc
./poc
Expected Output on 32-bit Systems:
k=10, x=1024
Calculated len: 1032
Allocated size: 8256 bytes
Actual required: 8216 bytes
Safe allocation
---------------------------------
k=20, x=1048576
Calculated len: 1048576
Allocated size: 8388608 bytes
Actual required: 8388616 bytes
Safe allocation
---------------------------------
k=28, x=268435456
Calculated len: 4
Allocated size: 32 bytes
Actual required: 1073741848 bytes
VULNERABLE: Under-allocation by 1073741816 bytes
---------------------------------
k=30, x=1073741824
Calculated len: 1
Allocated size: 8 bytes
Actual required: 4294967320 bytes
VULNERABLE: Under-allocation by 4294967312 bytes
---------------------------------
Impact:
- Heap buffer overflow when initializing Bigint structures
- Potential remote code execution via heap corruption
- Denial of service through application crashes
Affected Systems:
Primarily 32-bit architectures where:
size_t
is 32 bits- Large values of
k
(>26) are possible - Systems using the dtoa conversion with untrusted input
CPython versions tested on:
3.14, CPython main branch
Operating systems tested on:
Windows