Skip to content

Commit e40dd22

Browse files
vstinnermiss-islington
authored andcommitted
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 9398655) Co-authored-by: Victor Stinner <vstinner@python.org>
1 parent a6d25db commit e40dd22

1 file changed

Lines changed: 10 additions & 4 deletions

File tree

Objects/unicodeobject.c

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -961,10 +961,16 @@ xmlcharrefreplace(_PyBytesWriter *writer, char *str,
961961

962962
/* generate replacement */
963963
for (i = collstart; i < collend; ++i) {
964-
size = sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
965-
if (size < 0) {
966-
return NULL;
967-
}
964+
// Use snprintf() with a temporary buffer to not write the trailing
965+
// NUL byte in the writer buffer.
966+
Py_BUILD_ASSERT(_Py_MAX_UNICODE <= 0x10ffff);
967+
// len('&#1114111;\0') is 11 bytes.
968+
char buffer[11];
969+
Py_UCS4 ch = PyUnicode_READ(kind, data, i);
970+
size = snprintf(buffer, sizeof(buffer), "&#%d;", ch);
971+
assert(4 <= size && (size_t)size <= (sizeof(buffer) - 1));
972+
973+
memcpy(str, buffer, size);
968974
str += size;
969975
}
970976
return str;

0 commit comments

Comments
 (0)