From d04b504fc504f707bc894bbb9ed3a3e1f9813f90 Mon Sep 17 00:00:00 2001 From: Zackery Spytz Date: Fri, 25 Oct 2019 23:46:40 -0600 Subject: [PATCH 1/2] bpo-35714: Reject null characters in struct format strings struct.error is now raised if there is a null character in a struct format string. --- Lib/test/test_struct.py | 7 +++++++ .../next/Library/2019-10-25-23-45-49.bpo-35714.fw3xb7.rst | 2 ++ Modules/_struct.c | 5 +++++ 3 files changed, 14 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2019-10-25-23-45-49.bpo-35714.fw3xb7.rst diff --git a/Lib/test/test_struct.py b/Lib/test/test_struct.py index 157efa1347a9ba..076aaeba65060b 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', '\144\u0064\000xf', 'd\0d', '>ih\0', '=Q\0\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 cc536b46a623ec..fd65d8b683f685 100644 --- a/Modules/_struct.c +++ b/Modules/_struct.c @@ -1290,6 +1290,11 @@ 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(_structmodulestate_global->StructError, + "embedded null character"); + return -1; + } f = whichtable(&fmt); From c22bbbc4be8e9c90da5d1a78115a2dcf414bfcd2 Mon Sep 17 00:00:00 2001 From: Zackery Spytz Date: Fri, 17 Apr 2020 03:45:51 -0600 Subject: [PATCH 2/2] Fewer test cases. --- Lib/test/test_struct.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/test/test_struct.py b/Lib/test/test_struct.py index 3ddb8aba46f1b0..b3f21ea7db49ef 100644 --- a/Lib/test/test_struct.py +++ b/Lib/test/test_struct.py @@ -673,7 +673,7 @@ def __del__(self): def test_issue35714(self): # Embedded null characters should not be allowed in format strings. - for s in '\0', '\144\u0064\000xf', 'd\0d', '>ih\0', '=Q\0\0': + for s in '\0', '2\0i', b'\0': with self.assertRaisesRegex(struct.error, 'embedded null character'): struct.calcsize(s)