Python: imageop Unsafe Arithmetic
The imageop module's check_multiply_size() function used integer division without checking for remainders, allowing a size check to pass incorrectly. An attacker could supply crafted arguments to functions like grey2rgb, causing a buffer overflow that may lead to arbitrary code execution.
Originally disclosed on HackerOne
- Fixed in 39 days
- Paid in 39 days
- Disclosed after 9 days
http://bugs.python.org/issue24264
Several functions within the imageop module are vulnerable to exploitable buffer overflows due to unsafe arithmetic in check_multiply_size(). The problem exists because the check to confirm that size == product / y / x does not take remainders into account.
static int
check_multiply_size(int product, int x, const char* xname, int y, const char* yname, int size)
{
if ( !check_coordonnate(x, xname) )
return 0;
if ( !check_coordonnate(y, yname) )
return 0;
if ( size == (product / y) / x )
return 1;
PyErr_SetString(ImageopError, "String has incorrect length");
return 0;
}
Consider a call to check_multiply_size() where product is 16, x is 1, and y is 9. In the Windows x86 release of Python 2.7.9, the division is performed using the idiv instruction:
0:000> dV
product = 0n16
x = 0n1
xname = 0x1e1205a4 "x"
y = 0n9
yname = 0x1e127ab8 "y"
size = 0n1
0:000> u eip
python27!check_multiply_size+0x25 [c:\build27\cpython\modules\imageop.c @ 53]:
1e0330e5 f7ff idiv eax,edi
1e0330e7 99 cdq
1e0330e8 f7fe idiv eax,esi
1e0330ea 3944240c cmp dword ptr [esp+0Ch],eax
1e0330ee 7506 jne python27!check_multiply_size+0x36 (1e0330f6)
1e0330f0 b801000000 mov eax,1
1e0330f5 c3 ret
1e0330f6 8b15e47e241e mov edx,dword ptr [python27!ImageopError (1e247ee4)]
0:000> ?eax
Evaluate expression: 16 = 00000010
0:000> ?edi
Evaluate expression: 9 = 00000009
When the first idiv instruction is executed, the result (eax) is 1 with a remainder of 7 (edx):
0:000> p
eax=00000001 ebx=00000000 ecx=1e127ab8 edx=00000007 esi=00000001 edi=00000009
eip=1e0330e7 esp=0027fcec ebp=00000001 iopl=0 nv up ei pl nz na po nc
cs=0023 ss=002b ds=002b es=002b fs=0053 gs=002b efl=00000202
python27!check_multiply_size+0x27:
1e0330e7 99 cdq
0:000> ?eax
Evaluate expression: 1 = 00000001
0:000> ?edx
Evaluate expression: 7 = 00000007
Because size is 1, the check passes:
Breakpoint 4 hit
eax=00000001 ebx=00000000 ecx=1e127ab8 edx=00000000 esi=00000001 edi=00000009
eip=1e0330f0 esp=0027fcec ebp=00000001 iopl=0 nv up ei pl zr na pe nc
cs=0023 ss=002b ds=002b es=002b fs=0053 gs=002b efl=00000246
python27!check_multiply_size+0x30:
1e0330f0 b801000000 mov eax,1
This is problematic because some of the imageop functions, such as grey2rgb, utilize check_multiply_size() to check divisibility prior to copying data into a buffer. Consider a call to grey2rgb where x is 1, y is 9, and len is 16.
static PyObject *
imageop_grey2rgb(PyObject *self, PyObject *args)
{
int x, y, len, nlen; <<<<<<<< x = 1, y = 9, and len = 16.
unsigned char *cp;
unsigned char *ncp;
PyObject *rv;
int i;
unsigned char value;
int backward_compatible = imageop_backward_compatible();
if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
return 0;
if ( !check_multiply(len, x, y) ) <<<<<<<< 16 != 1 * 9, but this check still passes.
return 0;
nlen = x*y*4; <<<<<<<< 1 * 9 * 4 == 36.
if ( !check_multiply_size(nlen, x, "x", y, "y", 4) )
return 0;
rv = PyString_FromStringAndSize(NULL, nlen); <<<<<<<< This creates a buffer of length 36.
if ( rv == 0 )
return 0;
ncp = (unsigned char *)PyString_AsString(rv); <<<<<<<< This retrieves the buffer of length 36.
for ( i=0; i < len; i++ ) { <<<<<<<< This loop assumes that len * 4 == nlen, which is incorrect
in this case.
value = *cp++;
if (backward_compatible) {
VVVVVVVV Each iteration copies 4 bytes into the 36 byte buffer pointed to by ncp and
advances the pointer by 4. Because len is 16, 64 bytes are ultimately copied
into the buffer, leading to an exploitable buffer overflow condition.
* (Py_UInt32 *) ncp = (Py_UInt32) value | ((Py_UInt32) value << 8 ) | ((Py_UInt32) value << 16);
ncp += 4;
} else {
*ncp++ = 0;
*ncp++ = value;
*ncp++ = value;
*ncp++ = value;
}
}
return rv;
}
When the call completes, memory has been corrupted:
0:000> g
(12f4.640): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
eax=00444444 ebx=00000001 ecx=1e201d98 edx=00303030 esi=1e201d98 edi=1e201d98
eip=1e031fc6 esp=0027fe7c ebp=00000002 iopl=0 nv up ei ng nz ac pe cy
cs=0023 ss=002b ds=002b es=002b fs=0053 gs=002b efl=00010297
python27!update_refs+0x6:
1e031fc6 8b5010 mov edx,dword ptr [eax+10h] ds:002b:00444454=????????
0:000> g
(12f4.640): Access violation - code c0000005 (!!! second chance !!!)
eax=00444444 ebx=00000001 ecx=1e201d98 edx=00303030 esi=1e201d98 edi=1e201d98
eip=1e031fc6 esp=0027fe7c ebp=00000002 iopl=0 nv up ei ng nz ac pe cy
cs=0023 ss=002b ds=002b es=002b fs=0053 gs=002b efl=00010297
python27!update_refs+0x6:
1e031fc6 8b5010 mov edx,dword ptr [eax+10h] ds:002b:00444454=????????
During fuzzing, DEP access violations were encountered, so it should be assumed that this vulnerability can be exploited to achieve arbitrary code execution. To fix this vulnerability, it is recommended that check_multiply_size() confirm divisibility.
Context
The target is the imageop module of CPython, the C extension that provides a set of routines for manipulating images stored as plain byte strings. The module is part of the legacy Python 2 standard library and is written in C, so its argument handling and buffer management are the responsibility of the extension code itself rather than the interpreter's object layer.
Several functions in the module share a common validation helper, check_multiply_size(), whose job is to confirm that a caller-supplied buffer length is consistent with the declared image geometry. The report shows that this helper performs its arithmetic in a way that accepts lengths which are not actually consistent, and that at least one caller (grey2rgb) then copies more data than the destination buffer can hold.
The issue was filed as CPython issue 24264 and reported through the Internet Bug Bounty programme against the Python (Legacy) asset. The researcher is johnleitch, the report was disclosed on 2015-05-31, and a bounty of 1000.00 USD was awarded.
Setup
The analysis was carried out against the Windows x86 release of Python 2.7.9, using a debugger to step through the compiled check_multiply_size() and to observe the register state around the division instructions. The report does not describe any additional tooling, accounts or configuration beyond the debugger session and the fuzzing that produced the DEP access violations mentioned at the end.
The precondition for the bug is simply the ability to call the affected imageop functions with attacker-influenced geometry arguments. In an application that passes user-controlled dimensions or lengths into imageop, that condition is met directly.
Finding it
The researcher focused on check_multiply_size(), which is used by several functions in the module to validate that a size matches a product divided by the two coordinates:
static int
check_multiply_size(int product, int x, const char* xname, int y, const char* yname, int size)
{
if ( !check_coordonnate(x, xname) )
return 0;
if ( !check_coordonnate(y, yname) )
return 0;
if ( size == (product / y) / x )
return 1;
PyErr_SetString(ImageopError, "String has incorrect length");
return 0;
}
The problem is that the comparison size == (product / y) / x uses integer division and ignores the remainder. A product that is not an exact multiple of y and x can still produce a quotient equal to size, so the check passes even though the dimensions do not actually divide the product.
Exploitation
Step 1: Confirm the arithmetic in the debugger
The researcher considered a call where product is 16, x is 1 and y is 9. In the Windows x86 build, the division is compiled to the idiv instruction:
0:000> dV
product = 0n16
x = 0n1
xname = 0x1e1205a4 "x"
y = 0n9
yname = 0x1e127ab8 "y"
size = 0n1
0:000> u eip
python27!check_multiply_size+0x25 [c:\build27\cpython\modules\imageop.c @ 53]:
1e0330e5 f7ff idiv eax,edi
1e0330e7 99 cdq
1e0330e8 f7fe idiv eax,esi
1e0330ea 3944240c cmp dword ptr [esp+0Ch],eax
1e0330ee 7506 jne python27!check_multiply_size+0x36 (1e0330f6)
1e0330f0 b801000000 mov eax,1
1e0330f5 c3 ret
1e0330f6 8b15e47e241e mov edx,dword ptr [python27!ImageopError (1e247ee4)]
0:000> ?eax
Evaluate expression: 16 = 00000010
0:000> ?edi
Evaluate expression: 9 = 00000009
The disassembly shows the two divisions and the comparison of the quotient in eax against the size argument on the stack. At this point eax holds the product (16) and edi holds y (9).
Step 2: Observe the truncated quotient
Stepping over the first idiv shows the quotient and remainder:
The quotient is 1 and the remainder is 7. The remainder is discarded, so the subsequent division by x (1) leaves the quotient at 1.
Step 3: Watch the check pass
Because size is 1, the comparison succeeds and the function returns success:
Step 4: Trace the consequence in grey2rgb
The report explains why this matters by looking at a caller such as grey2rgb, which uses check_multiply_size() to check divisibility before copying data into a buffer. The annotated source for a call where x is 1, y is 9 and len is 16 is:
static PyObject *
imageop_grey2rgb(PyObject *self, PyObject *args)
{
int x, y, len, nlen; <<<<<<<< x = 1, y = 9, and len = 16.
unsigned char *cp;
unsigned char *ncp;
PyObject *rv;
int i;
unsigned char value;
int backward_compatible = imageop_backward_compatible();
if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
return 0;
if ( !check_multiply(len, x, y) ) <<<<<<<< 16 != 1 * 9, but this check still passes.
return 0;
nlen = x*y*4; <<<<<<<< 1 * 9 * 4 == 36.
if ( !check_multiply_size(nlen, x, "x", y, "y", 4) )
return 0;
rv = PyString_FromStringAndSize(NULL, nlen); <<<<<<<< This creates a buffer of length 36.
if ( rv == 0 )
return 0;
ncp = (unsigned char *)PyString_AsString(rv); <<<<<<<< This retrieves the buffer of length 36.
for ( i=0; i < len; i++ ) { <<<<<<<< This loop assumes that len * 4 == nlen, which is incorrect
in this case.
value = *cp++;
if (backward_compatible) {
VVVVVVVV Each iteration copies 4 bytes into the 36 byte buffer pointed to by ncp and
advances the pointer by 4. Because len is 16, 64 bytes are ultimately copied
into the buffer, leading to an exploitable buffer overflow condition.
* (Py_UInt32 *) ncp = (Py_UInt32) value | ((Py_UInt32) value << 8 ) | ((Py_UInt32) value << 16);
ncp += 4;
} else {
*ncp++ = 0;
*ncp++ = value;
*ncp++ = value;
*ncp++ = value;
}
}
return rv;
}
The destination buffer is allocated with nlen = x*y*4, which is 36 bytes for these arguments. The copy loop, however, runs len times (16) and writes 4 bytes per iteration, so 64 bytes are written into a 36-byte buffer. The check_multiply_size() call that was supposed to catch the mismatch passed because of the truncated division described above.
Step 5: Observe the corruption
When the call completes, memory has been corrupted and the process faults:
The fault occurs in update_refs, with eax holding 0x00444444.
Root cause
The defect is the divisibility check in check_multiply_size(). The expression size == (product / y) / x performs integer division and discards remainders, so a product that is not an exact multiple of y and x can still yield a quotient equal to size. The helper therefore returns success for geometries that are not actually consistent.
Callers such as grey2rgb rely on this helper to guarantee that the number of bytes they will copy matches the size of the destination buffer. Because the helper accepts inconsistent values, the copy loop writes len * 4 bytes into a buffer of x*y*4 bytes, overflowing it. The existing validation did not stop the attack because the only guard against the mismatch was the flawed arithmetic itself.
Impact
An attacker who can control the arguments passed to the affected imageop functions can trigger a heap buffer overflow. The report notes that during fuzzing, DEP access violations were encountered, and states that it should be assumed the vulnerability can be exploited to achieve arbitrary code execution. The report does not enumerate which specific functions beyond grey2rgb are reachable in a given application, nor does it describe a full exploit chain; the arbitrary code execution claim is presented as an assumption based on the fuzzing results.
Fix
The report recommends that check_multiply_size() confirm divisibility, so that a product which is not an exact multiple of y and x is rejected rather than accepted on the basis of a truncated quotient. The report does not describe a specific patch or commit.
Variants to test
- Other
imageopfunctions that callcheck_multiply_size(): pass geometries where the product is not an exact multiple of the coordinates and observe whether the call is accepted. A positive result is a function that proceeds past validation and writes beyond its allocated buffer. - Different coordinate combinations: vary
xandyso that the remainder from the first division is non-zero, and check whether the quotient still equalssize. A positive result is a validation pass for a geometry that does not divide the product. - Length values larger than the geometry implies: supply a
lenthat exceedsx*yand observe whether the copy loop writes more thanx*y*4bytes. A positive result is memory corruption or a crash in the interpreter.
Hunting notes
This class of bug tends to hide in C extensions and native helpers that validate buffer sizes using integer arithmetic, particularly where division is used to check a product against a size. During recon, look for modules that parse dimensions or lengths from untrusted input and then allocate buffers based on those values; the presence of a helper named like check_multiply_size or any divisibility check is a signal worth reading closely.
The researcher demonstrated impact by stepping through the compiled check in a debugger, showing the truncated quotient and remainder, then tracing the resulting overflow in grey2rgb and capturing the access violation in update_refs. During fuzzing, DEP access violations were encountered, so the report says it should be assumed the bug can be exploited to achieve arbitrary code execution.
What happened, in plain words
Python ships with a module called imageop. It is a small set of tools for working with pictures that are stored as plain sequences of bytes, rather than as files you would open in a photo viewer. This module was written in C, the low-level language that Python itself is built from, and it belongs to the older Python 2 standard library. Because it is written in C, it has to look after its own memory: when it wants space to build a result, it asks the system for a block of memory of a certain size, and it is entirely responsible for never writing more into that block than it asked for.
Several functions in imageop share a helper function called check_multiply_size(). A helper is just a small piece of code that other pieces of code call to do a common job. This helper's job is to check that a length supplied by whoever called the function is consistent with the width and height of the image they described. The researcher found that this helper does its arithmetic in a way that accepts lengths which are not actually consistent, and that at least one function using it, grey2rgb, then copies more data into its output block than the block can hold. Writing past the end of a block of memory is called a buffer overflow, and it is one of the classic ways to make a program misbehave or, in the worst case, run an attacker's code.
The issue was filed as CPython issue 24264 (CPython is the main, reference implementation of Python) and reported through the Internet Bug Bounty programme, which pays researchers for finding security problems in widely used internet software. The asset was listed as Python (Legacy), meaning the older Python 2 line. The researcher is johnleitch, the report was disclosed on 2015-05-31, and a bounty of 1000.00 USD was awarded.
Context
The target is the imageop module of CPython. It is a C extension: a piece of software written in C that plugs into Python and adds features the core language does not have. It provides routines for manipulating images that are stored as plain byte strings. A byte string is simply a run of bytes, where each byte is a number from 0 to 255; a picture can be represented this way by listing the colour value of each pixel in order. The module is part of the legacy Python 2 standard library, so it is old code that many programs may still import. Because it is written in C, its argument handling and buffer management are the responsibility of the extension code itself rather than the interpreter's object layer. In plain terms: Python normally protects you from memory mistakes, but code written in C steps outside that protection and must be careful on its own.
Several functions in the module share a common validation helper, check_multiply_size(). Validation means checking that the inputs make sense before doing any work. Its job is to confirm that a caller-supplied buffer length is consistent with the declared image geometry. Geometry here means the width and height of the image, and the buffer length is how many bytes the caller says they have. The report shows that this helper performs its arithmetic in a way that accepts lengths which are not actually consistent, and that at least one caller (grey2rgb) then copies more data than the destination buffer can hold. The destination buffer is the block of memory the function allocates to hold its result.
The issue was filed as CPython issue 24264 and reported through the Internet Bug Bounty programme against the Python (Legacy) asset.
Setup
The analysis was carried out against the Windows x86 release of Python 2.7.9. Windows x86 means the 32-bit build of Python for Windows. The researcher used a debugger, a tool that lets you pause a running program, look at its internal state, and step through it one machine instruction at a time. Machine instructions are the individual commands the processor actually executes; a debugger shows them to you and lets you run them one by one. The debugger was used to step through the compiled check_multiply_size() and to observe the register state around the division instructions. Registers are tiny, very fast storage slots inside the processor; the debugger can show you what number each one currently holds.
The report does not describe any additional tooling, accounts or configuration beyond the debugger session and the fuzzing that produced the DEP access violations mentioned at the end. Fuzzing means feeding a program large amounts of slightly varied input automatically, hoping to make it crash, and then studying the crashes. DEP stands for Data Execution Prevention, a Windows feature that stops the processor from running code stored in memory regions that should only hold data; a DEP access violation is the operating system stepping in when a program tries to do exactly that.
The precondition for the bug is simply the ability to call the affected imageop functions with attacker-influenced geometry arguments. In an application that passes user-controlled dimensions or lengths into imageop, that condition is met directly. In other words, if a web service or program lets a user say how wide and tall an image is, and hands those numbers to imageop, the attacker controls the very values that the flawed check gets wrong.
Finding it
The researcher focused on check_multiply_size(), which is used by several functions in the module to validate that a size matches a product divided by the two coordinates. The two coordinates are the width and the height. The product is the total number of bytes the caller claims to have. The helper divides the product by the height and then by the width, and compares the result with the size the caller supplied.
static int
check_multiply_size(int product, int x, const char* xname, int y, const char* yname, int size)
{
if ( !check_coordonnate(x, xname) )
return 0;
if ( !check_coordonnate(y, yname) )
return 0;
if ( size == (product / y) / x )
return 1;
PyErr_SetString(ImageopError, "String has incorrect length");
return 0;
}
Line by line, in plain words:
static intand the function name declare a helper that returns a whole number, where 1 means success and 0 means failure.staticjust means it is private to this file.- The parameters are the product (total bytes claimed), the two coordinates
xandywith their names for error messages, and thesizethe caller supplied. check_coordonnate(x, xname)and the same call foryfirst make sure each coordinate is a sensible positive number. If either is not, the helper returns 0, meaning failure.if ( size == (product / y) / x )is the heart of the bug. It divides the product byy, then divides that result byx, and asks whether the answer equalssize. If it does, the helper returns 1, meaning success.- If the comparison fails, the helper records an error message saying the string has an incorrect length and returns 0.
The problem is that the comparison size == (product / y) / x uses integer division and ignores the remainder. Integer division means dividing whole numbers and throwing away anything after the decimal point: 16 divided by 9 is 1 remainder 7, and integer division keeps only the 1. A product that is not an exact multiple of y and x can still produce a quotient equal to size, so the check passes even though the dimensions do not actually divide the product. A quotient is simply the result of a division. The helper is therefore answering the wrong question: it asks whether the rounded-down answer matches, instead of whether the division was exact.
Exploitation
Step 1: Confirm the arithmetic in the debugger
The researcher considered a call where product is 16, x is 1 and y is 9. In the Windows x86 build, the division is compiled to the idiv instruction. idiv is the processor's signed integer division instruction; it takes a number, divides it by another, and leaves the quotient in one register and the remainder in another.
0:000> dV
product = 0n16
x = 0n1
xname = 0x1e1205a4 "x"
y = 0n9
yname = 0x1e127ab8 "y"
size = 0n1
0:000> u eip
python27!check_multiply_size+0x25 [c:\build27\cpython\modules\imageop.c @ 53]:
1e0330e5 f7ff idiv eax,edi
1e0330e7 99 cdq
1e0330e8 f7fe idiv eax,esi
1e0330ea 3944240c cmp dword ptr [esp+0Ch],eax
1e0330ee 7506 jne python27!check_multiply_size+0x36 (1e0330f6)
1e0330f0 b801000000 mov eax,1
1e0330f5 c3 ret
1e0330f6 8b15e47e241e mov edx,dword ptr [python27!ImageopError (1e247ee4)]
0:000> ?eax
Evaluate expression: 16 = 00000010
0:000> ?edi
Evaluate expression: 9 = 00000009
What each part shows:
dVis a debugger command that displays the local variables of the current function. It listsproductas 16,xas 1,yas 9 andsizeas 1. The0nprefix just means "this is a decimal number".u eipasks the debugger to disassemble, that is, show the machine instructions, starting at the current instruction pointer. The instruction pointer is the register that says which instruction is about to run.- The first
idiv eax,edidivides the value ineaxby the value inedi. The secondidiv eax,esidivides the result by the value inesi. cdqis a small housekeeping instruction that prepares the processor for the next signed division.cmp dword ptr [esp+0Ch],eaxcompares thesizeargument, which sits on the stack, with the quotient ineax. The stack is a region of memory the program uses to keep track of function arguments and local values.jnemeans jump if not equal: if the comparison fails, the program jumps to the error path. Otherwise it runsmov eax,1andret, returning success.- The two
?eaxand?edicommands ask the debugger to print the current values of those registers. They confirmeaxholds the product (16) andediholdsy(9).
At this point eax holds the product (16) and edi holds y (9).
Step 2: Observe the truncated quotient
Stepping over the first idiv shows the quotient and remainder. Stepping means letting the program execute exactly one instruction and then pausing again.
What this shows:
- The
pcommand runs one instruction. The line of register values afterwards is the debugger's snapshot of the processor state. eax=00000001means the quotient is 1.edx=00000007means the remainder is 7. The processor did the division honestly and kept both parts.- The
?eaxand?edxcommands print those two registers to confirm: quotient 1, remainder 7.
The quotient is 1 and the remainder is 7. The remainder is discarded, so the subsequent division by x (1) leaves the quotient at 1. Dividing by 1 changes nothing, so the rounded-down answer stays 1 even though 16 is not a multiple of 9.
Step 3: Watch the check pass
Because size is 1, the comparison succeeds and the function returns success.
A breakpoint is a marker the researcher placed on a particular instruction so the debugger pauses there. The snapshot shows the program has reached the instruction that loads 1 into eax, which is the success return value. The check has passed. This is the moment the bug becomes real: the helper has just told its caller that a length of 1 is consistent with a product of 16 and coordinates of 1 and 9, which is false.
Step 4: Trace the consequence in grey2rgb
The report explains why this matters by looking at a caller such as grey2rgb, which uses check_multiply_size() to check divisibility before copying data into a buffer. grey2rgb uses check_multiply_size() to check divisibility before copying data into a buffer. The annotated source for a call where x is 1, y is 9 and len is 16 is:
static PyObject *
imageop_grey2rgb(PyObject *self, PyObject *args)
{
int x, y, len, nlen; <<<<<<<< x = 1, y = 9, and len = 16.
unsigned char *cp;
unsigned char *ncp;
PyObject *rv;
int i;
unsigned char value;
int backward_compatible = imageop_backward_compatible();
if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
return 0;
if ( !check_multiply(len, x, y) ) <<<<<<<< 16 != 1 * 9, but this check still passes.
return 0;
nlen = x*y*4; <<<<<<<< 1 * 9 * 4 == 36.
if ( !check_multiply_size(nlen, x, "x", y, "y", 4) )
return 0;
rv = PyString_FromStringAndSize(NULL, nlen); <<<<<<<< This creates a buffer of length 36.
if ( rv == 0 )
return 0;
ncp = (unsigned char *)PyString_AsString(rv); <<<<<<<< This retrieves the buffer of length 36.
for ( i=0; i < len; i++ ) { <<<<<<<< This loop assumes that len * 4 == nlen, which is incorrect
in this case.
value = *cp++;
if (backward_compatible) {
VVVVVVVV Each iteration copies 4 bytes into the 36 byte buffer pointed to by ncp and
advances the pointer by 4. Because len is 16, 64 bytes are ultimately copied
into the buffer, leading to an exploitable buffer overflow condition.
* (Py_UInt32 *) ncp = (Py_UInt32) value | ((Py_UInt32) value << 8 ) | ((Py_UInt32) value << 16);
ncp += 4;
} else {
*ncp++ = 0;
*ncp++ = value;
*ncp++ = value;
*ncp++ = value;
}
}
return rv;
}
Line by line, in plain words:
int x, y, len, nlen;declares four whole numbers: the width, the height, the length of the input, and the length of the output. The comment marks the values used in this example: width 1, height 9, input length 16.unsigned char *cp;andunsigned char *ncp;declare two pointers. A pointer is a variable that holds a memory address, like a slip of paper with a house number on it.cpwill point at the input bytes andncpat the output bytes.PyObject *rv;declares a pointer to a Python object, which will become the returned result.int i;is the loop counter, andunsigned char value;holds one byte read from the input.int backward_compatible = imageop_backward_compatible();asks whether the module is running in its older compatibility mode, which changes how bytes are written.PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y)unpacks the arguments the caller passed in. The format string"s#ii"says: a byte string with its length, then two integers. It fills incp,len,xandy. If the arguments do not match, the function returns 0.check_multiply(len, x, y)is a first check; the comment notes that 16 is not 1 times 9, yet this check still passes.nlen = x*y*4;computes the output size: width times height times four bytes per pixel, which is 36 here.check_multiply_size(nlen, x, "x", y, "y", 4)calls the flawed helper to confirm that the output size is consistent with the geometry. This is the call that wrongly succeeds because of the truncated division.PyString_FromStringAndSize(NULL, nlen)asks Python for a new byte string of 36 bytes. This is the destination buffer.PyString_AsString(rv)gets a pointer to the bytes inside that new string, so the code can write into them directly.for ( i=0; i < len; i++ )loops once per input byte, so 16 times. The comment explains the assumption behind the loop: that four output bytes per input byte will exactly fill the output buffer. With these numbers that assumption is wrong.value = *cp++;reads one input byte and moves the input pointer forward by one.- In the compatibility branch, the long expression packs the same value into three of the four bytes of a 32-bit word and writes that word at
ncp, thenncp += 4moves the output pointer forward by four. Each pass therefore writes four bytes. - In the other branch, four separate assignments write four bytes one at a time, again advancing
ncpeach time. return rv;hands the finished string back to the caller.
The destination buffer is allocated with nlen = x*y*4, which is 36 bytes for these arguments. The copy loop, however, runs len times (16) and writes 4 bytes per iteration, so 64 bytes are written into a 36-byte buffer. The check_multiply_size() call that was supposed to catch the mismatch passed because of the truncated division described above. Think of booking a 36-seat room and then letting 64 guests in: the first 36 fit, and the rest spill into whatever is next door.
Step 5: Observe the corruption
When the call completes, memory has been corrupted and the process faults. A fault, or access violation, is the operating system stopping the program because it touched memory it should not have.
What this shows:
gmeans go: resume running the program until something interesting happens.Access violation - code c0000005is Windows reporting that the program tried to read or write memory it is not allowed to touch. The first chance is the first report, which the program's own error handling might still deal with; the second chance means it was not handled and the process is being stopped.- The fault occurs in
update_refs, a Python internal routine that walks through objects to keep track of how many references point at them. It is not part ofimageop; it is simply the next piece of code that touched the damaged memory. eax=00444444is the value the code was trying to use as an address when the fault occurred.
Root cause
The defect is the divisibility check in check_multiply_size(). The expression size == (product / y) / x performs integer division and discards remainders, so a product that is not an exact multiple of y and x can still yield a quotient equal to size. The helper therefore returns success for geometries that are not actually consistent. Divisibility means one number divides another exactly, with nothing left over; the helper never checks that.
Callers such as grey2rgb rely on this helper to guarantee that the number of bytes they will copy matches the size of the destination buffer. Because the helper accepts inconsistent values, the copy loop writes len * 4 bytes into a buffer of x*y*4 bytes, overflowing it. The existing validation did not stop the attack because the only guard against the mismatch was the flawed arithmetic itself. There was no second line of defence behind it.
Impact
An attacker who can control the arguments passed to the affected imageop functions can trigger a heap buffer overflow. The heap is the general-purpose pool of memory a program uses for objects it creates while running; a heap buffer overflow means writing past the end of one of those objects into neighbouring memory. The report notes that during fuzzing, DEP access violations were encountered, and states that it should be assumed the vulnerability can be exploited to achieve arbitrary code execution. Arbitrary code execution means getting the processor to run instructions the attacker chose, which is the most serious outcome for a memory bug. The report does not enumerate which specific functions beyond grey2rgb are reachable in a given application, nor does it describe a full exploit chain; the arbitrary code execution claim is presented as an assumption based on the fuzzing results.
Fix
The report recommends that check_multiply_size() confirm divisibility, so that a product which is not an exact multiple of y and x is rejected rather than accepted on the basis of a truncated quotient. In everyday terms: instead of asking whether the rounded-down answer looks right, ask whether anything was left over. The report does not describe a specific patch or commit.
Variants to test
- Other
imageopfunctions that callcheck_multiply_size(): pass geometries where the product is not an exact multiple of the coordinates and observe whether the call is accepted. A positive result is a function that proceeds past validation and writes beyond its allocated buffer. - Different coordinate combinations: vary
xandyso that the remainder from the first division is non-zero, and check whether the quotient still equalssize. A positive result is a validation pass for a geometry that does not divide the product. - Length values larger than the geometry implies: supply a
lenthat exceedsx*yand observe whether the copy loop writes more thanx*y*4bytes. A positive result is memory corruption or a crash in the interpreter.
Hunting notes
This class of bug tends to hide in C extensions and native helpers that validate buffer sizes using integer arithmetic, particularly where division is used to check a product against a size. During recon, look for modules that parse dimensions or lengths from untrusted input and then allocate buffers based on those values; the presence of a helper named like check_multiply_size or any divisibility check is a signal worth reading closely. Recon here means the early survey of a target to decide where to spend effort.
The researcher demonstrated impact by stepping through the compiled check in a debugger, showing the truncated quotient and remainder, then tracing the resulting overflow in grey2rgb and capturing the access violation in update_refs. During fuzzing, DEP access violations were encountered, so the report says it should be assumed the bug can be exploited to achieve arbitrary code execution.
Glossary
- Access violation: the operating system stopping a program because it tried to read or write memory it is not allowed to touch.
- Arbitrary code execution: getting a computer to run instructions chosen by an attacker rather than by the program's author.
- Asset: the specific piece of software or system a bug bounty report is about.
- Breakpoint: a marker placed on an instruction so a debugger pauses the program there.
- Buffer: a block of memory set aside to hold data, such as the output of a conversion.
- Buffer overflow: writing more data into a buffer than it has room for, so the extra data spills into neighbouring memory.
- Byte: a unit of data made of eight bits, able to hold a number from 0 to 255.
- Byte string: a sequence of bytes, often used to represent raw data such as image pixels.
- C: a low-level programming language in which Python itself and many of its extensions are written.
- C extension: code written in C that plugs into Python and adds features the core language does not have.
- Caller: the piece of code that calls a function.
- CPython: the main, reference implementation of the Python language.
- Debugger: a tool that lets you pause a running program, inspect its internal state and step through it instruction by instruction.
- DEP (Data Execution Prevention): a Windows feature that stops the processor from running code stored in memory regions meant only for data.
- Destination buffer: the block of memory a function allocates to hold its result.
- Disassemble: turn machine code back into readable instructions.
- Divisibility: the property of one number dividing another exactly, with no remainder.
- Division, integer: dividing whole numbers and discarding anything after the decimal point.
- Fault: see access violation.
- Fuzzing: automatically feeding a program large amounts of varied input to make it crash, then studying the crashes.
- Geometry: the width and height of an image.
- Heap: the general-purpose pool of memory a program uses for objects it creates while running.
- Helper: a small function that other code calls to do a common job.
- idiv: the processor's signed integer division instruction, which leaves a quotient and a remainder.
- Imageop: a legacy Python 2 module, written in C, for manipulating images stored as byte strings.
- Instruction: a single command the processor executes.
- Instruction pointer: the register that says which instruction is about to run.
- Internet Bug Bounty: a programme that pays researchers for finding security problems in widely used internet software.
- Legacy: older software kept for compatibility, in this case the Python 2 line.
- Machine code: the instructions the processor actually runs.
- Pointer: a variable that holds a memory address.
- Product: in this report, the total number of bytes a caller claims to have.
- Quotient: the result of a division.
- Recon: the early survey of a target to decide where to spend effort.
- Register: a tiny, very fast storage slot inside the processor.
- Remainder: what is left over after a division that does not come out exactly.
- Stack: a region of memory a program uses to keep track of function arguments and local values.
- Stepping: letting a program execute one instruction and then pausing again.
- Truncated quotient: a quotient with its remainder thrown away.
- Validation: checking that inputs make sense before doing any work.
- Windows x86: the 32-bit build of software for Windows.