From 93021c635d2291b5ec50aa02d4d0956d502b714a Mon Sep 17 00:00:00 2001 From: "Christoph M. Becker" Date: Fri, 30 Aug 2024 19:13:44 +0200 Subject: [PATCH] Fix GH-15628: php_stream_memory_get_buffer() not zero-terminated We're reasonably sure that appending the NUL is not an OOB write, since the memory stream implementation uses `zend_string` APIs instead of fiddling with the buffer. We don't add a regression test because that would require to set up something in the zend_test extension, and regressions are supposed to be caught by external consumers of this API, such as mailparse. Closes GH-15648. --- NEWS | 4 ++++ main/streams/memory.c | 2 ++ 2 files changed, 6 insertions(+) diff --git a/NEWS b/NEWS index c0f9a89f60c..9921764951f 100644 --- a/NEWS +++ b/NEWS @@ -25,6 +25,10 @@ PHP NEWS . Fixed bug GH-15432 (Heap corruption when querying a vector). (cmb, Kamil Tekiela) +- Streams: + . Fixed bug GH-15628 (php_stream_memory_get_buffer() not zero-terminated). + (cmb) + 29 Aug 2024, PHP 8.2.23 - Core: diff --git a/main/streams/memory.c b/main/streams/memory.c index f53084a6c3a..9e5952eaad6 100644 --- a/main/streams/memory.c +++ b/main/streams/memory.c @@ -60,6 +60,7 @@ static ssize_t php_stream_memory_write(php_stream *stream, const char *buf, size if (count) { ZEND_ASSERT(buf != NULL); memcpy(ZSTR_VAL(ms->data) + ms->fpos, (char*) buf, count); + ZSTR_VAL(ms->data)[ZSTR_LEN(ms->data)] = '\0'; ms->fpos += count; } return count; @@ -240,6 +241,7 @@ static int php_stream_memory_set_option(php_stream *stream, int option, int valu size_t old_size = ZSTR_LEN(ms->data); ms->data = zend_string_realloc(ms->data, newsize, 0); memset(ZSTR_VAL(ms->data) + old_size, 0, newsize - old_size); + ZSTR_VAL(ms->data)[ZSTR_LEN(ms->data)] = '\0'; } return PHP_STREAM_OPTION_RETURN_OK; }