Skip to content

Signed integer overflow in main/streams/streams.c #15980

Closed

Description

@YuanchengJiang

Description

The following code:

<?php
$file_modes = array( "w","wb","wt","w+","w+b","w+t",
"x","xb","xt","x+","x+b","x+t");
$file_content_types = array( "text_with_new_line","alphanumeric");
$offset = array(-1,0,1,PHP_INT_MAX,600); // different offsets
$filename = __DIR__."/fseek_ftell_rewind_variation6.tmp"; // this is name of the file created by create_files()
foreach($file_content_types as $file_content_type){
foreach($file_modes as $file_mode) {
$file_handle = fopen($filename, $file_mode);
foreach($offset as $count){
var_dump( fseek($file_handle,$count,SEEK_CUR) );
} //end of offset loop
} //end of file_mode loop
} //end of file_content_types loop

Resulted in this output:

/php-src/main/streams/streams.c:1385:31: runtime error: signed integer overflow: 1 + 9223372036854775807 cannot be represented in type 'long'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /php-src/main/streams/streams.c:1385:31 in

PHP Version

PHP 8.4.0-dev

Operating System

ubuntu 22.04

Activity

  1. cmb69 commented on Sep 22, 2024

    @cmb69
    Member

    Simple reproducer:

    <?php
    $s = fopen(__FILE__, "r");
    fseek($s, 1);
    fseek($s, PHP_INT_MAX, SEEK_CUR);

    Possible fix:

     main/streams/streams.c | 7 ++++++-
     1 file changed, 6 insertions(+), 1 deletion(-)
    
    diff --git a/main/streams/streams.c b/main/streams/streams.c
    index f3fb5e3cda..0fbb1a13fc 100644
    --- a/main/streams/streams.c
    +++ b/main/streams/streams.c
    @@ -1382,7 +1382,12 @@ PHPAPI int _php_stream_seek(php_stream *stream, zend_off_t offset, int whence)
     
     		switch(whence) {
     			case SEEK_CUR:
    -				offset = stream->position + offset;
    +				ZEND_ASSERT(stream->position >= 0);
    +				if (offset > ZEND_LONG_MAX - stream->position) {
    +					offset = ZEND_LONG_MAX;
    +				} else {
    +					offset = stream->position + offset;
    +				}
     				whence = SEEK_SET;
     				break;
     		}

    Older PHP versions are likely affected as well.

  2. self-assigned this
    on Sep 22, 2024
  3. added a commit that references this issue on Sep 22, 2024
    ff09d9a
  4. added 2 commits that reference this issue on Sep 22, 2024
    6a04c79
    c701508
  5. added 3 commits that reference this issue on Sep 22, 2024
    10008fb
    ee95ee7
    a9fcf49
  6. 1 remaining item

  7. cmb69 commented on Sep 22, 2024

    @cmb69
    Member

    I had to revert, so reopening.

  8. reopened this on Sep 22, 2024
  9. added 3 commits that reference this issue on Sep 24, 2024
    acee803
    f44250c
    8191675
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions