https://github.com/python/cpython/commit/0decd77786fa726f83ffbe357d954e78c8f682e4 commit: 0decd77786fa726f83ffbe357d954e78c8f682e4 branch: 3.15 author: Miss Islington (bot) <[email protected]> committer: hugovk <[email protected]> date: 2026-09-11T21:06:13+03:00 summary:
[3.15] gh-156939: Fix xmlcharrefreplace() buffer overflow (GH-157109) (#157232) Co-authored-by: Victor Stinner <[email protected]> files: M Objects/unicodeobject.c diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c index c3a1beee0c8a5e..ad24bc5d83933a 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; _______________________________________________ Python-checkins mailing list -- [email protected] To unsubscribe send an email to [email protected] https://mail.python.org/mailman3//lists/python-checkins.python.org Member address: [email protected]
