From ea7233ca0ff28056d3c41082084975535b062e33 Mon Sep 17 00:00:00 2001 From: Zackery Spytz Date: Mon, 25 May 2020 01:55:09 -0600 Subject: [PATCH] bpo-35714: Reject null characters in struct format strings (GH-16928) struct.error is now raised if there is a null character in a struct format string. (cherry picked from commit 3f59b55316f4c6ab451997902579aa69020b537c) Co-authored-by: Zackery Spytz --- Lib/test/test_struct.py | 8 ++++++++ .../next/Library/2019-10-25-23-45-49.bpo-35714.fw3xb7.rst | 2 ++ Modules/_struct.c | 5 +++++ 3 files changed, 15 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 be0047589cb465..1a068cb46bf40e 100644 --- a/Lib/test/test_struct.py +++ b/Lib/test/test_struct.py @@ -579,6 +579,14 @@ def test__sizeof__(self): self.check_sizeof('0c', 0) + 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): """ Tests for iterative unpacking (struct.Struct.iter_unpack). 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 cd3fa2d150673b..2e9ff9c98987ad 100644 --- a/Modules/_struct.c +++ b/Modules/_struct.c @@ -1295,6 +1295,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);