Skip to content

Commit 4ea8028

Browse files
[3.8] bpo-35714: Reject null characters in struct format strings (GH-16928) (GH-20419)
struct.error is now raised if there is a null character in a struct format string. (cherry picked from commit 3f59b55) (cherry picked from commit 5ff5edf) Co-authored-by: Zackery Spytz <zspytz@gmail.com>
1 parent b068d89 commit 4ea8028

3 files changed

Lines changed: 13 additions & 0 deletions

File tree

Lib/test/test_struct.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -626,6 +626,13 @@ def test_format_attr(self):
626626
s2 = struct.Struct(s.format.encode())
627627
self.assertEqual(s2.format, s.format)
628628

629+
def test_issue35714(self):
630+
# Embedded null characters should not be allowed in format strings.
631+
for s in '\0', '2\0i', b'\0':
632+
with self.assertRaisesRegex(struct.error,
633+
'embedded null character'):
634+
struct.calcsize(s)
635+
629636

630637
class UnpackIteratorTest(unittest.TestCase):
631638
"""
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:exc:`struct.error` is now raised if there is a null character in a
2+
:mod:`struct` format string.

Modules/_struct.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1285,6 +1285,10 @@ prepare_s(PyStructObject *self)
12851285
size_t ncodes;
12861286

12871287
fmt = PyBytes_AS_STRING(self->s_format);
1288+
if (strlen(fmt) != (size_t)PyBytes_GET_SIZE(self->s_format)) {
1289+
PyErr_SetString(StructError, "embedded null character");
1290+
return -1;
1291+
}
12881292

12891293
f = whichtable(&fmt);
12901294

0 commit comments

Comments
 (0)