Skip to content

Segfault when a stream finalizes the HashContext during hash_update_stream() or hash_update_file() #25957

Done

Description

@thunderer

Description

The following code:

<?php
class Wrapper {
    public $context;

    public function stream_open($path, $mode, $options, &$opened_path) {
        return true;
    }

    public function stream_read($count) {
        hash_final($GLOBALS['ctx']);
        return "data";
    }

    public function stream_eof() {
        return false;
    }
}

stream_wrapper_register("finalize", Wrapper::class);
$ctx = hash_init("md5");
var_dump(hash_update_stream($ctx, fopen("finalize://", "r")));
echo "done\n";

Resulted in this output:

Segmentation fault (core dumped)

With ASAN (PHP-8.4):

ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000
    #0 PHP_MD5Update ext/standard/md5.c:309
    #1 zif_hash_update_stream ext/hash/hash.c:742

But I expected this output instead:

Fatal error: Uncaught TypeError: hash_update_stream(): Argument #1 ($context) must be a valid, non-finalized HashContext

hash_update_stream() and hash_update_file() check the context once, before the loop. A user stream wrapper (stream_open() or stream_read()) or a php_user_filter runs during php_stream_read(). If it calls hash_final(), the context is freed and set to NULL, and the next hash_update call uses the NULL context. hash_update_file() crashes in the same way (ext/hash/hash.c:777).

I have a patch with a test and will open a PR against PHP-8.4.

PHP Version

PHP 8.5.12 (cli) (built: Oct 28 2026 01:20:43) (NTS)
Copyright (c) The PHP Group
Built by https://github.com/docker-library/php
Zend Engine v4.5.12, Copyright (c) Zend Technologies
    with Zend OPcache v8.5.12, Copyright (c), by Zend Technologies

Also reproduced with PHP 7.4 to 8.6 (official Docker images) and the current PHP-8.4, PHP-8.5, PHP-8.6 and master branches.

Operating System

Debian 13 (official php:8.5-cli Docker image)

Activity

  1. added a commit that references this issue on Dec 1, 2026
    440c523
  2. added a commit that references this issue on Dec 1, 2026
    126976d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions