Skip to content

Commit 672a380

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 9c193bd commit 672a380

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
@@ -938,10 +938,16 @@ xmlcharrefreplace(_PyBytesWriter *writer, char *str,
938938

939939
/* generate replacement */
940940
for (i = collstart; i < collend; ++i) {
941-
size = sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
942-
if (size < 0) {
943-
return NULL;
944-
}
941+
// Use snprintf() with a temporary buffer to not write the trailing
942+
// NUL byte in the writer buffer.
943+
Py_BUILD_ASSERT(_Py_MAX_UNICODE <= 0x10ffff);
944+
// len('&#1114111;\0') is 11 bytes.
945+
char buffer[11];
946+
Py_UCS4 ch = PyUnicode_READ(kind, data, i);
947+
size = snprintf(buffer, sizeof(buffer), "&#%d;", ch);
948+
assert(4 <= size && (size_t)size <= (sizeof(buffer) - 1));
949+
950+
memcpy(str, buffer, size);
945951
str += size;
946952
}
947953
return str;

0 commit comments

Comments
 (0)