Skip to content

Commit ddc944a

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 311df8c commit ddc944a

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
@@ -875,10 +875,16 @@ xmlcharrefreplace(PyBytesWriter *writer, char *str,
875875

876876
/* generate replacement */
877877
for (i = collstart; i < collend; ++i) {
878-
size = sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
879-
if (size < 0) {
880-
return NULL;
881-
}
878+
// Use snprintf() with a temporary buffer to not write the trailing
879+
// NUL byte in the writer buffer.
880+
Py_BUILD_ASSERT(_Py_MAX_UNICODE <= 0x10ffff);
881+
// len('&#1114111;\0') is 11 bytes.
882+
char buffer[11];
883+
Py_UCS4 ch = PyUnicode_READ(kind, data, i);
884+
size = snprintf(buffer, sizeof(buffer), "&#%d;", ch);
885+
assert(4 <= size && (size_t)size <= (sizeof(buffer) - 1));
886+
887+
memcpy(str, buffer, size);
882888
str += size;
883889
}
884890
return str;

0 commit comments

Comments
 (0)