From 62dce97973436f1830b18304e7939a03b18d44ba Mon Sep 17 00:00:00 2001 From: Nikita Popov Date: Thu, 27 Aug 2020 15:49:33 +0200 Subject: Require non-negative length in stream_get_contents() If the length is not -1, require it to be non-negative. Using such lengths doesn't make sense (as only -1 is special-case to read in chunks, anything else will end up doing a huge upfront allocation) and can lead to string allocation overflow. A similar check is already in place for file_get_contents(). That one does not allow -1 (and uses null instead), but this function is explicitly specified to accept -1, so stick to that behavior. --- ext/standard/streamsfuncs.c | 5 +++++ .../streams/stream_get_contents_negative_length.phpt | 16 ++++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 ext/standard/tests/streams/stream_get_contents_negative_length.phpt diff --git a/ext/standard/streamsfuncs.c b/ext/standard/streamsfuncs.c index 493f3d0864..99632a6de8 100644 --- a/ext/standard/streamsfuncs.c +++ b/ext/standard/streamsfuncs.c @@ -442,6 +442,11 @@ PHP_FUNCTION(stream_get_contents) Z_PARAM_LONG(desiredpos) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); + if (maxlen < 0 && maxlen != PHP_STREAM_COPY_ALL) { + php_error_docref(NULL, E_WARNING, "Length must be greater than or equal to zero, or -1"); + RETURN_FALSE; + } + php_stream_from_zval(stream, zsrc); if (desiredpos >= 0) { diff --git a/ext/standard/tests/streams/stream_get_contents_negative_length.phpt b/ext/standard/tests/streams/stream_get_contents_negative_length.phpt new file mode 100644 index 0000000000..3d52729a2f --- /dev/null +++ b/ext/standard/tests/streams/stream_get_contents_negative_length.phpt @@ -0,0 +1,16 @@ +--TEST-- +stream_get_contents() with negative max length +--FILE-- + +--EXPECTF-- +string(2) "bc" + +Warning: stream_get_contents(): Length must be greater than or equal to zero, or -1 in %s on line %d +bool(false) -- cgit v1.2.1