Skip to content

Commit

Permalink
Require non-negative length in stream_get_contents()
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
nikic committed Aug 27, 2020
1 parent 1b7ee6d commit 62dce97
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
5 changes: 5 additions & 0 deletions ext/standard/streamsfuncs.c
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
--TEST--
stream_get_contents() with negative max length
--FILE--
<?php

$tmp = tmpfile();
fwrite($tmp, "abcd");
var_dump(stream_get_contents($tmp, 2, 1));
var_dump(stream_get_contents($tmp, -2));

?>
--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)

0 comments on commit 62dce97

Please sign in to comment.