From ddc944a5e99153fac46c695e6a1d1b596f39b9bb Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Wed, 9 Sep 2026 15:18:22 -0400 Subject: [PATCH] gh-156939: Fix xmlcharrefreplace() buffer overflow (GH-157109) Write into a temporary buffer to not write the trailing NUL byte into the writer. Previously, the NUL byte was written outsize the writer buffer. (cherry picked from commit 939865532c00e25842209f56953abe0361ab22a1) Co-authored-by: Victor Stinner --- Objects/unicodeobject.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c index c3a1beee0c8a5e7..ad24bc5d83933a0 100644 --- a/Objects/unicodeobject.c +++ b/Objects/unicodeobject.c @@ -875,10 +875,16 @@ xmlcharrefreplace(PyBytesWriter *writer, char *str, /* generate replacement */ for (i = collstart; i < collend; ++i) { - size = sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i)); - if (size < 0) { - return NULL; - } + // Use snprintf() with a temporary buffer to not write the trailing + // NUL byte in the writer buffer. + Py_BUILD_ASSERT(_Py_MAX_UNICODE <= 0x10ffff); + // len('􏿿\0') is 11 bytes. + char buffer[11]; + Py_UCS4 ch = PyUnicode_READ(kind, data, i); + size = snprintf(buffer, sizeof(buffer), "&#%d;", ch); + assert(4 <= size && (size_t)size <= (sizeof(buffer) - 1)); + + memcpy(str, buffer, size); str += size; } return str;