Skip to content

ext/zip: fix use-after-free in the archive destructor path - #23779

Closed
jvoisin wants to merge 2 commits into
php:masterfrom
jvoisin:uaf
Closed

jvoisin wants to merge 2 commits into
php:masterfrom
jvoisin:uaf

Conversation

@jvoisin

@jvoisin jvoisin commented Sep 19, 2026

Copy link
Copy Markdown
Contributor

Commit 132403d guarded php_zipobj_close() and ZipArchive::open() with the archive->close flag so that a progress or cancel callback firing during zip_close() cannot re-enter and run a nested zip_close() followed by zip_discard(), which frees the archive still in use.

php_zip_archive_release() was left unguarded. php_zipobj_close() sets archive->za = NULL before calling release(), so the close() path is safe, but when a ZipArchive is destroyed without an explicit close() the archive is finalized here with za still set. The progress/cancel callback fires during that zip_close(), and a re-entrant close() or open() then nests zip_close() on the same archive, causing the same use-after-free.

Set archive->close around the release-path zip_close() as well, so the re-entrant call throws "Already being closed" instead of nesting.

Commit 132403d guarded php_zipobj_close() and ZipArchive::open()
with the archive->close flag so that a progress or cancel callback
firing during zip_close() cannot re-enter and run a nested zip_close()
followed by zip_discard(), which frees the archive still in use.

php_zip_archive_release() was left unguarded. php_zipobj_close() sets
archive->za = NULL before calling release(), so the close() path is
safe, but when a ZipArchive is destroyed without an explicit close()
the archive is finalized here with za still set. The progress/cancel
callback fires during that zip_close(), and a re-entrant close() or
open() then nests zip_close() on the same archive, causing the same
use-after-free.

Set archive->close around the release-path zip_close() as well, so the
re-entrant call throws "Already being closed" instead of nesting.
@devnexen

Copy link
Copy Markdown
Member

suggestion (does not have to be in the same PR, but since the goal is to "plug" cases where the zip stream close):

  • protecting the getStream() case that can still reach the assert (I think adding php_zipobj_closing check is enough).
  • guarding php_zip_progress_callback_free like php_zip_progress_callback does ?

Other than that, the fix itself here is correct from my POV.

@jvoisin

jvoisin commented Sep 21, 2026

Copy link
Copy Markdown
Contributor Author

suggestion (does not have to be in the same PR, but since the goal is to "plug" cases where the zip stream close):

* protecting the getStream() case that can still reach the assert (I think adding php_zipobj_closing check is enough).

* guarding php_zip_progress_callback_free like php_zip_progress_callback does ?

Other than that, the fix itself here is correct from my POV.

Yeah, good points, I piled a commit doing this on top of the initial one

@devnexen

Copy link
Copy Markdown
Member

Could these tests be added ?

this one, normally should pass with your branch

--TEST--
GH-23747 (re-entrant close()/getStream() from a callback fired by the ZipArchive destructor)
--EXTENSIONS--
zip
--SKIPIF--
<?php
if (!method_exists(ZipArchive::class, 'registerProgressCallback')) {
    die('skip progress callbacks are not supported');
}
?>
--FILE--
<?php
function populate(ZipArchive $zip, string $filename): void {
    $zip->open($filename, ZipArchive::CREATE | ZipArchive::OVERWRITE);
    for ($i = 0; $i < 64; $i++) {
        $zip->addFromString("f$i.txt", str_repeat('x', 2000));
    }
}

$filename = __DIR__ . '/gh23747_dtor.zip';

$zip = new ZipArchive();
populate($zip, $filename);
$weak = WeakReference::create($zip);
$zip->registerProgressCallback(0.0, function ($rate) use ($weak) {
    static $done = false;
    if ($done) {
        return;
    }
    $done = true;
    try {
        $weak->get()->close();
    } catch (Error $e) {
        echo $e::class, ': ', $e->getMessage(), PHP_EOL;
    }
});
unset($zip);
echo 'destroyed', PHP_EOL;

$zip = new ZipArchive();
populate($zip, $filename);
$weak = WeakReference::create($zip);
$zip->registerProgressCallback(0.0, function ($rate) use ($weak) {
    static $done = false;
    if ($done) {
        return;
    }
    $done = true;
    try {
        $weak->get()->getStreamName('f0.txt');
    } catch (Error $e) {
        echo $e::class, ': ', $e->getMessage(), PHP_EOL;
    }
});
unset($zip);
echo 'destroyed', PHP_EOL;
?>
--CLEAN--
<?php
@unlink(__DIR__ . '/gh23747_dtor.zip');
?>
--EXPECT--
Error: Already being closed
destroyed
Error: Already being closed
destroyed

however, not sure about this one

$dir = __DIR__ . '/zdir'; @mkdir($dir);
$zip = new ZipArchive();
$zip->open($dir . '/t.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
for ($i = 0; $i < 8; $i++) { $zip->addFromString("f$i.txt", str_repeat('x', 200)); }
set_error_handler(function ($no, $str) use ($zip) {
    static $done = false;
    if ($done) { return true; }
    $done = true;
    try { var_dump($zip->close()); }
    catch (Error $e) { echo $e::class, ': ', $e->getMessage(), PHP_EOL; }
    return true;
});
chmod($dir, 0555);
var_dump($zip->close());

…t close

Follow-up to the archive destructor use-after-free fix, plugging two more
paths where a progress or cancel callback firing during zip_close() can
re-enter the archive.

getStream() reached php_zip_archive_addref() with the archive already being
closed (refcount 0), tripping the ZEND_ASSERT(refcount > 0). Guard it with
php_zipobj_closing() so the call throws "Already being closed" instead.

Guard php_zip_progress_callback_free() and php_zip_cancel_callback_free()
like their callback counterparts, so the FCC destructor is not run while the
engine is inactive or in a bailout.
@jvoisin

jvoisin commented Sep 21, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for taking the time to write the tests, I should have been the one doing it in the first place :/

@devnexen

Copy link
Copy Markdown
Member

One last thing I did not notice, target branch should be PHP-8.4. CI should be green so LGTM but I ll let Weilin handles the matter.

@jvoisin

jvoisin commented Sep 21, 2026

Copy link
Copy Markdown
Contributor Author

One last thing I did not notice, target branch should be PHP-8.4. CI should be green so LGTM but I ll let Weilin handles the matter.

Why should it target 8.4?

@LamentXU123

Copy link
Copy Markdown
Member

Because this is a bugfix. And our lowest bugfix support minor version is 8.4 :)

@jvoisin

jvoisin commented Sep 21, 2026

Copy link
Copy Markdown
Contributor Author

The other PR I sent recently to address heap corruptions (#23818, #23814, #23771, #23770, …) were all against the master branch, and were merged there :/

@LamentXU123

Copy link
Copy Markdown
Member

I think they were wrongly merged. I will take care of backporting them :)

@LamentXU123 LamentXU123 left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Nice work!
Last thing, please rebase this to 8.4. I've talked to other people about your previous fixes about whether they should be backport and we'll see. At least it is nice to have this patch in stable branches. Thank you.

Update: They are backported.

LamentXU123 added a commit that referenced this pull request Oct 8, 2026
* PHP-8.6:
  ext/zip: Fix use-after-free in the archive destructor path (#23779)
@LamentXU123

Copy link
Copy Markdown
Member

Thank you!

Ti-Mis pushed a commit to Ti-Mis/php-src that referenced this pull request Oct 8, 2026
* PHP-8.4:
  ext/zip: Fix use-after-free in the archive destructor path (php#23779)
Ti-Mis pushed a commit to Ti-Mis/php-src that referenced this pull request Oct 8, 2026
* PHP-8.5:
  ext/zip: Fix use-after-free in the archive destructor path (php#23779)
damek24 pushed a commit to damek24/php-src that referenced this pull request Oct 8, 2026
A progress or cancel callback runs inside zip_close() after libzip has
fixed the list of entries it writes. Deleting or unchanging an entry from
the callback frees a dirent that zip_close() still uses. Other changes are
either silently dropped or make close() fail and lose the archive.

Reject archive mutations with the same "Already being closed" Error that
close() and open() already raise, using php_zipobj_closing(). This follows
phpGH-23749 and complements the destructor protection in phpGH-23779.

Cover progress callbacks, cancel callbacks, and the implicit close() in
open(), and verify that the archive contents are preserved.

Closes php#24025
arnaud-lb added a commit to frodeborli/php-src that referenced this pull request Oct 9, 2026
* up/master: (180 commits)
  Changed the test expected result of `pdo_mysql/bug76815_pdo_mysql_f to %d (php#13808)
  ext/standard: name the real parameter in the unpack() offset error (php#24215)
  ext/readline: Refactor CLI readline completion generators
  Fix phpGH-24081: User opcode DISPATCH runs on a stale frame in the TAILCALL VM
  ext/standard: Validate the bcrypt cost before reading it
  JIT: Avoid object type check if the object is known to be a type (php#24086)
  zend_alloc: move a small block shrunk to the size of the bin below
  Fix phpGH-23979: Nullsafe operator must not flush delayed oplines of an enclosing function
  ext/zip: Reject ZipArchive mutators during close() (php#24025)
  Fix OSS-Fuzz #568005340: FETCH_DIM_FUNC_ARG partial conversion
  Fix too wide type inference for ASSIGN_DIM_OP
  Fix type inference of ADD_ARRAY_UNPACK with integer keys
  Evaluate ZEND_SPACESHIP in SCCP
  Add range inference for SPACESHIP
  JIT: Optimize array checks in comparisons (php#24084)
  Fix leak when the added previous exception is already in the chain (php#24177)
  date: Add `php_date_time_duration_create()` in a new `time_duration.h` (php#24072)
  ext/zip: Fix use-after-free in the archive destructor path (php#23779)
  ext/standard: Optimize array_chunk() by filling packed chunks directly
  Fix phpGH-17626: JIT corrupts opline handler when blacklisting root trace
  ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants