py/modstruct: Check and prevent buffer-write overflow in struct packing.

Prior to this patch, the size of the buffer given to pack_into() was checked
for being too small by using the count of the arguments, not their actual
size.  For example, a format spec of '4I' would only check that there was 4
bytes available, not 16; and 'I' would check for 1 byte, not 4.

The pack() function is ok because its buffer is created to be exactly the
correct size.

The fix in this patch calculates the total size of the format spec at the
start of pack_into() and verifies that the buffer is large enough.  This
adds some computational overhead, to iterate through the whole format spec.
The alternative is to check during the packing, but that requires extra
code to handle alignment, and the check is anyway not needed for pack().
So to maintain minimal code size the check is done using struct_calcsize.
This commit is contained in:
Damien George
2017-09-01 11:11:09 +10:00
parent 79d5acbd01
commit 2daacc5cee
3 changed files with 26 additions and 13 deletions

View File

@@ -69,6 +69,12 @@ print(buf)
struct.pack_into('<bbb', buf, -6, 0x44, 0x45, 0x46)
print(buf)
# check that we get an error if the buffer is too small
try:
struct.pack_into('I', bytearray(1), 0, 0)
except:
print('struct.error')
try:
struct.pack_into('<bbb', buf, 7, 0x41, 0x42, 0x43)
except: