php-src icon indicating copy to clipboard operation
php-src copied to clipboard

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

Open ArtUkrainskiy opened this issue 2 weeks ago • 0 comments

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

ArtUkrainskiy avatar Nov 17 '26 17:11 ArtUkrainskiy