Skip to content

Commit aead53b

Browse files
johanliuzhangyangyu
authored andcommitted
bpo-30245: Fix possible overflow when organize struct.pack_into error message (python#1682)
1 parent cdb89cd commit aead53b

File tree

4 files changed

+19
-2
lines changed

4 files changed

+19
-2
lines changed

Lib/test/test_struct.py

+10
Original file line numberDiff line numberDiff line change
@@ -599,6 +599,16 @@ def test_boundary_error_message_with_negative_offset(self):
599599
'offset -11 out of range for 10-byte buffer'):
600600
struct.pack_into('<B', byte_list, -11, 123)
601601

602+
def test_boundary_error_message_with_large_offset(self):
603+
# Test overflows cause by large offset and value size (issue 30245)
604+
regex = (
605+
r'pack_into requires a buffer of at least ' + str(sys.maxsize + 4) +
606+
r' bytes for packing 4 bytes at offset ' + str(sys.maxsize) +
607+
r' \(actual buffer size is 10\)'
608+
)
609+
with self.assertRaisesRegex(struct.error, regex):
610+
struct.pack_into('<I', bytearray(10), sys.maxsize, 1)
611+
602612
def test_issue29802(self):
603613
# When the second argument of struct.unpack() was of wrong type
604614
# the Struct object was decrefed twice and the reference to

Misc/ACKS

+1
Original file line numberDiff line numberDiff line change
@@ -921,6 +921,7 @@ Gregor Lingl
921921
Everett Lipman
922922
Mirko Liss
923923
Alexander Liu
924+
Yuan Liu
924925
Nick Lockwood
925926
Stephanie Lockwood
926927
Martin von Löwis

Misc/NEWS

+3
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,9 @@ Extension Modules
345345
Library
346346
-------
347347

348+
- bpo-30245: Fix possible overflow when organize struct.pack_into
349+
error message. Patch by Yuan Liu.
350+
348351
- bpo-30378: Fix the problem that logging.handlers.SysLogHandler cannot
349352
handle IPv6 addresses.
350353

Modules/_struct.c

+5-2
Original file line numberDiff line numberDiff line change
@@ -1929,11 +1929,14 @@ s_pack_into(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames
19291929

19301930
/* Check boundaries */
19311931
if ((buffer.len - offset) < soself->s_size) {
1932+
assert(offset >= 0);
1933+
assert(soself->s_size >= 0);
1934+
19321935
PyErr_Format(StructError,
1933-
"pack_into requires a buffer of at least %zd bytes for "
1936+
"pack_into requires a buffer of at least %zu bytes for "
19341937
"packing %zd bytes at offset %zd "
19351938
"(actual buffer size is %zd)",
1936-
soself->s_size + offset,
1939+
(size_t)soself->s_size + (size_t)offset,
19371940
soself->s_size,
19381941
offset,
19391942
buffer.len);

0 commit comments

Comments
 (0)