diff --git a/Lib/test/test_struct.py b/Lib/test/test_struct.py index 454082e66d3f86..67e7c559d9f1d2 100644 --- a/Lib/test/test_struct.py +++ b/Lib/test/test_struct.py @@ -652,6 +652,13 @@ def test_format_attr(self): s2 = struct.Struct(s.format.encode()) self.assertEqual(s2.format, s.format) + def test_issue35714(self): + # Embedded null characters should not be allowed in format strings. + for s in '\0', '2\0i', b'\0': + with self.assertRaisesRegex(struct.error, + 'embedded null character'): + struct.calcsize(s) + class UnpackIteratorTest(unittest.TestCase): """ diff --git a/Misc/NEWS.d/next/Library/2019-10-25-23-45-49.bpo-35714.fw3xb7.rst b/Misc/NEWS.d/next/Library/2019-10-25-23-45-49.bpo-35714.fw3xb7.rst new file mode 100644 index 00000000000000..39102065ca7b51 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2019-10-25-23-45-49.bpo-35714.fw3xb7.rst @@ -0,0 +1,2 @@ +:exc:`struct.error` is now raised if there is a null character in a +:mod:`struct` format string. diff --git a/Modules/_struct.c b/Modules/_struct.c index 1c917b7513f467..64a9827e83aaee 100644 --- a/Modules/_struct.c +++ b/Modules/_struct.c @@ -1285,6 +1285,10 @@ prepare_s(PyStructObject *self) size_t ncodes; fmt = PyBytes_AS_STRING(self->s_format); + if (strlen(fmt) != (size_t)PyBytes_GET_SIZE(self->s_format)) { + PyErr_SetString(StructError, "embedded null character"); + return -1; + } f = whichtable(&fmt);