Skip to content

Phar::setSignatureAlgorithm(): OpenSSL signing reads a freed private key #25528

Closed

Description

@ArtUkrainskiy

Description

Phar::setSignatureAlgorithm(Phar::OPENSSL, $key) keeps a pointer into the $key string in PHAR_G(openssl_privatekey) and doesn't copy it. Here the key string from file_get_contents() is freed right after the call, and the next write to the phar signs it with freed memory. The pointer also outlives the request.

<?php
// a key file to sign with
$key = openssl_pkey_new(['private_key_type' => OPENSSL_KEYTYPE_RSA, 'private_key_bits' => 2048]);
openssl_pkey_export_to_file($key, __DIR__ . '/private.pem');

$phar = new Phar(__DIR__ . '/test.phar');
$phar->addFromString('a.txt', 'a');
$phar->setSignatureAlgorithm(Phar::OPENSSL, file_get_contents(__DIR__ . '/private.pem'));
$phar->addFromString('b.txt', 'b');
var_dump($phar->getSignature()['hash_type']);

With -d phar.readonly=0, on an ASan build with USE_ZEND_ALLOC=0.

Resulted in this output:

ERROR: AddressSanitizer: heap-use-after-free
READ of size 28
    ...
    #10 PEM_read_bio_PrivateKey_ex
    #11 phar_create_signature ext/phar/util.c:1883
    #12 phar_flush_ex ext/phar/phar.c:3027
    #13 phar_flush ext/phar/phar.c:2491
    #14 phar_add_file ext/phar/phar_object.c:3690
    #15 zim_Phar_addFromString ext/phar/phar_object.c:3894

But I expected this output instead:

string(7) "OpenSSL"

Without ASan it fails once the freed memory is reused: PharException: phar error: unable to write signature: unable to process private key.

I'm opening a PR that keeps a copy of the key.

PHP Version

PHP 8.7.0-dev (master). The same code is in 8.4, 8.5 and 8.6.

Operating System

Ubuntu 26.04, OpenSSL 3.5.5

Activity

  1. added 3 commits that reference this issue on Nov 22, 2026
    9af7194
    f2faa48
    8bc0295
  2. added a commit that references this issue on Nov 22, 2026
    97adf31
  3. added a commit that references this issue on Nov 24, 2026
    70188a5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions