From 8d0b4d80c96140f0074c5aaae16cd14f55e5e0dc Mon Sep 17 00:00:00 2001 From: Andreas Gohr Date: Tue, 24 Nov 2026 16:51:35 +0000 Subject: [PATCH 1/7] Trust only the central directory sizes and stop at truncated tar data Zip::extract() replaced the sizes and the CRC from the central directory with the values from the local file header. A local header could declare a much larger size than the central directory, so a size check based on contents() did not limit what extract() wrote. The central directory now supplies these values. The ZIP specification allows local values only to be zero or masked. Tar::extract() continued its copy loop after the end of the archive. A 10 KB tar with a pax size of 99999999999999 kept the process busy without end. Skipping an excluded entry in a bzip2 archive had the same problem. Extraction now throws an ArchiveCorruptedException on missing data and removes the partial file, and skipping stops at the end of the file. --- src/Tar.php | 23 ++++++++++++------ src/Zip.php | 10 +------- tests/TarTestCase.php | 51 ++++++++++++++++++++++++++++++++++++++++ tests/ZipTestCase.php | 26 ++++++++++++++++++++ tests/tar/truncated.tar | Bin 0 -> 10240 bytes 5 files changed, 94 insertions(+), 16 deletions(-) create mode 100644 tests/tar/truncated.tar diff --git a/src/Tar.php b/src/Tar.php index 192b37d..ed17bb1 100644 --- a/src/Tar.php +++ b/src/Tar.php @@ -254,12 +254,19 @@ public function extract($outdir, $strip = '', $exclude = '', $include = '') throw new ArchiveIOException('Could not open file for writing: '.$output); } - $size = floor($header['size'] / 512); - for ($i = 0; $i < $size; $i++) { - fwrite($fp, $this->readbytes(512), 512); - } - if (($header['size'] % 512) != 0) { - fwrite($fp, $this->readbytes(512), $header['size'] % 512); + $size = $header['size']; + while ($size > 0) { + $read_size = min($size, 512); + $buffer = $this->readbytes(512); + if (strlen($buffer) < $read_size) { + fclose($fp); + @unlink($output); + throw new ArchiveCorruptedException( + 'Could not read the expected data for '.$header['filename'] + ); + } + fwrite($fp, $buffer, $read_size); + $size -= $read_size; } fclose($fp); @@ -562,7 +569,9 @@ protected function skipbytes($bytes) // bzread allows to read a max of 8kb at once while($bytes) { $toread = min(8192, $bytes); - @bzread($this->fh, $toread); + if (!strlen((string) @bzread($this->fh, $toread))) { + break; // end of file + } $bytes -= $toread; } } else { diff --git a/src/Zip.php b/src/Zip.php index 641544c..8c65c2e 100644 --- a/src/Zip.php +++ b/src/Zip.php @@ -774,16 +774,8 @@ protected function readFileHeader($header) // $header['extradata'] is kept as what the central directory provided } + // sizes and CRC are kept from the central directory, the local values may be zero or masked $header['compression'] = $data['compression']; - foreach (array( - 'size', - 'compressed_size', - 'crc' - ) as $hd) { // On ODT files, these headers are 0. Keep the previous value. - if ($data[$hd] != 0) { - $header[$hd] = $data[$hd]; - } - } $header['flag'] = $data['flag']; $header['mtime'] = $this->makeUnixTime($data['mdate'], $data['mtime']); diff --git a/tests/TarTestCase.php b/tests/TarTestCase.php index ff4889e..a0f9c1d 100644 --- a/tests/TarTestCase.php +++ b/tests/TarTestCase.php @@ -1062,6 +1062,57 @@ public function testFilePropertiesPreservation() unlink($archive); } + /** + * An entry with less data than its declared size must be rejected and its partial file removed. + */ + public function testTruncatedEntryExtract() + { + $dir = $this->getDir() . '/tar'; + $out = sys_get_temp_dir() . '/phpa-truncated-out-' . md5(uniqid('', true)); + + $tar = new Tar(); + $tar->open("$dir/truncated.tar"); + try { + $tar->extract($out); + $this->fail('Extracting a truncated entry did not fail'); + } catch (ArchiveCorruptedException $e) { + $this->assertFileNotExists("$out/truncated.txt"); + } finally { + self::RDelete($out); + } + } + + /** + * Skipping an excluded entry with less data than its declared size must stop at the end of the archive. + */ + public function testTruncatedEntrySkip() + { + $dir = $this->getDir() . '/tar'; + $data = file_get_contents("$dir/truncated.tar"); + $archives = array('tar' => $data); + if (extension_loaded('zlib')) { + $archives['tgz'] = gzencode($data); + } + if (extension_loaded('bz2')) { + $archives['tbz'] = bzcompress($data); + } + + foreach ($archives as $ext => $content) { + $tmp = sys_get_temp_dir() . '/phpa-truncated-' . md5(uniqid('', true)) . '.' . $ext; + $out = sys_get_temp_dir() . '/phpa-truncated-out-' . md5(uniqid('', true)); + file_put_contents($tmp, $content); + + $tar = new Tar(); + $tar->open($tmp); + try { + $this->assertEquals(array(), $tar->extract($out, '', '/truncated/'), $ext); + } finally { + self::RDelete($out); + unlink($tmp); + } + } + } + /** * recursive rmdir()/unlink() * diff --git a/tests/ZipTestCase.php b/tests/ZipTestCase.php index 31b23a3..74478f5 100644 --- a/tests/ZipTestCase.php +++ b/tests/ZipTestCase.php @@ -176,6 +176,32 @@ public function testStoredEntryExceedingArchiveSize() } } + /** + * Sizes in the local file header that differ from the central directory must be ignored. + */ + public function testLocalHeaderSizesIgnored() + { + $raw = 'hello'; + $deflated = gzdeflate($raw, 9); + + $blob = $this->craftZip('local.txt', $deflated, 8, strlen($deflated), strlen($raw), crc32($raw)); + $blob = substr_replace($blob, pack('VV', 0x7FFFFFFF, 0x7FFFFFFF), 18, 8); // local sizes + + $tmp = sys_get_temp_dir() . '/phpa-local-' . md5(uniqid('', true)) . '.zip'; + $out = sys_get_temp_dir() . '/phpa-local-out-' . md5(uniqid('', true)); + file_put_contents($tmp, $blob); + + $zip = new Zip(); + $zip->open($tmp); + try { + $zip->extract($out); + $this->assertStringEqualsFile("$out/local.txt", $raw); + } finally { + self::RDelete($out); + @unlink($tmp); + } + } + /** * A deflated entry shorter than its declared uncompressed size must be rejected. */ diff --git a/tests/tar/truncated.tar b/tests/tar/truncated.tar new file mode 100644 index 0000000000000000000000000000000000000000..4a0d54362e991f8c3dab008280e10b6f69f2c3c5 GIT binary patch literal 10240 zcmeIxF%H5Y7=~eHPr(T&MXYf!adh+w#4@-zP?``=Z%NZZ5=Xl5{sW{yC_Lm-o$786 zm+sz;K8Px%*Ajnvt<8Cx%S(jrwdt*psmf`JP3I}Pu>8IlZspS)<@Eaa>*c2otz5tP zd&V%opDy}Q#S|-P Date: Tue, 24 Nov 2026 16:51:42 +0000 Subject: [PATCH 2/7] Add limits for the size and the number of extracted entries Callers that extract untrusted archives had no way to stop an archive that expands to a very large size or to very many files. setExtractionSizeLimit() and setExtractionFileLimit() set a maximum for the total bytes and the number of entries that extract() writes. Before each entry, extract() compares the declared size with the remaining limit and throws an ArchiveLimitException when the entry would exceed it. Files extracted up to that point stay on disk. Entries skipped by the include and exclude filters do not count. Both limits default to 0, which means no limit. --- src/Archive.php | 56 +++++++++++++++++++++++++ src/ArchiveLimitException.php | 10 +++++ src/Tar.php | 7 ++++ src/Zip.php | 8 ++++ tests/TarTestCase.php | 79 +++++++++++++++++++++++++++++++++++ tests/ZipTestCase.php | 79 +++++++++++++++++++++++++++++++++++ 6 files changed, 239 insertions(+) create mode 100644 src/ArchiveLimitException.php diff --git a/src/Archive.php b/src/Archive.php index 45c87fd..342ab6e 100644 --- a/src/Archive.php +++ b/src/Archive.php @@ -13,6 +13,12 @@ abstract class Archive /** @var callable */ protected $callback; + /** @var int maximum number of bytes extract() may write, 0 for no limit */ + protected $extractionSizeLimit = 0; + + /** @var int maximum number of entries extract() may create, 0 for no limit */ + protected $extractionFileLimit = 0; + /** * Set the compression level and type * @@ -64,6 +70,7 @@ abstract public function contents(); * @param string $exclude a regular expression of files to exclude * @param string $include a regular expression of files to include * @throws ArchiveIOException + * @throws ArchiveLimitException * @return array */ abstract public function extract($outdir, $strip = '', $exclude = '', $include = ''); @@ -132,4 +139,53 @@ public function setCallback($callback) { $this->callback = $callback; } + + /** + * Set the maximum total size of all files written by extract() + * + * The extraction is aborted with an ArchiveLimitException before an entry would exceed the limit. Files + * extracted up to that point are not removed. + * + * @param int $bytes the maximum number of bytes, 0 for no limit + */ + public function setExtractionSizeLimit($bytes) + { + $this->extractionSizeLimit = (int) $bytes; + } + + /** + * Set the maximum number of entries created by extract() + * + * Files and directories count as entries, skipped entries do not. The extraction is aborted with an + * ArchiveLimitException before an entry would exceed the limit. Files extracted up to that point are not + * removed. + * + * @param int $files the maximum number of entries, 0 for no limit + */ + public function setExtractionFileLimit($files) + { + $this->extractionFileLimit = (int) $files; + } + + /** + * Check that extracting the next entry stays within the configured limits + * + * @param string $name the path of the entry, used in the error message + * @param int $files the number of entries including this one + * @param int $bytes the number of bytes written including this entry + * @throws ArchiveLimitException + */ + protected function checkExtractionLimits($name, $files, $bytes) + { + if ($this->extractionFileLimit && $files > $this->extractionFileLimit) { + throw new ArchiveLimitException( + 'Extracting '.$name.' exceeds the limit of '.$this->extractionFileLimit.' entries' + ); + } + if ($this->extractionSizeLimit && $bytes > $this->extractionSizeLimit) { + throw new ArchiveLimitException( + 'Extracting '.$name.' exceeds the limit of '.$this->extractionSizeLimit.' bytes' + ); + } + } } diff --git a/src/ArchiveLimitException.php b/src/ArchiveLimitException.php new file mode 100644 index 0000000..7eb3fea --- /dev/null +++ b/src/ArchiveLimitException.php @@ -0,0 +1,10 @@ +readbytes(512)) { // read the file header $header = $this->parseHeader($dat); @@ -240,6 +242,11 @@ public function extract($outdir, $strip = '', $exclude = '', $include = '') continue; } + if (!$fileinfo->getIsdir()) { + $written += $header['size']; + } + $this->checkExtractionLimits($fileinfo->getPath(), count($extracted) + 1, $written); + // create output directory $output = $outdir.'/'.$fileinfo->getPath(); $directory = ($fileinfo->getIsdir()) ? $output : dirname($output); diff --git a/src/Zip.php b/src/Zip.php index 8c65c2e..d27c854 100644 --- a/src/Zip.php +++ b/src/Zip.php @@ -145,6 +145,7 @@ public function yieldContents() * @param string $include a regular expression of files to include * @throws ArchiveIOException * @throws ArchiveCorruptedException + * @throws ArchiveLimitException * @return FileInfo[] */ public function extract($outdir, $strip = '', $exclude = '', $include = '') @@ -157,6 +158,7 @@ public function extract($outdir, $strip = '', $exclude = '', $include = '') @mkdir($outdir, 0777, true); $extracted = array(); + $written = 0; $cdir = $this->readCentralDir(); $pos_entry = $cdir['offset']; // begin of the central file directory @@ -179,6 +181,12 @@ public function extract($outdir, $strip = '', $exclude = '', $include = '') continue; } + // stored entries are copied as they are, all others are written with their uncompressed size + if (!$fileinfo->getIsdir()) { + $written += ($header['compression'] == 0) ? $header['compressed_size'] : $header['size']; + } + $this->checkExtractionLimits($fileinfo->getPath(), count($extracted) + 1, $written); + $extracted[] = $fileinfo; // create output directory diff --git a/tests/TarTestCase.php b/tests/TarTestCase.php index a0f9c1d..24dbc35 100644 --- a/tests/TarTestCase.php +++ b/tests/TarTestCase.php @@ -1113,6 +1113,85 @@ public function testTruncatedEntrySkip() } } + /** + * Create a tar archive with three files of ten bytes each + * + * @param string $file the path to save the archive to + */ + protected function createLimitArchive($file) + { + $tar = new Tar(); + $tar->create($file); + $tar->addData('one.txt', str_repeat('1', 10)); + $tar->addData('two.txt', str_repeat('2', 10)); + $tar->addData('three.txt', str_repeat('3', 10)); + $tar->close(); + } + + /** + * Extraction must stop before the entry that exceeds the size limit + */ + public function testExtractionSizeLimit() + { + foreach ($this->extensions as $ext) { + $tmp = sys_get_temp_dir() . '/phpa-limit-' . md5(uniqid('', true)) . '.' . $ext; + $out = sys_get_temp_dir() . '/phpa-limit-out-' . md5(uniqid('', true)); + $this->createLimitArchive($tmp); + + $tar = new Tar(); + $tar->setExtractionSizeLimit(30); + $tar->open($tmp); + $this->assertCount(3, $tar->extract($out), $ext); + self::RDelete($out); + + $tar = new Tar(); + $tar->setExtractionSizeLimit(25); + $tar->open($tmp); + try { + $tar->extract($out); + $this->fail("Size limit was not enforced for $ext"); + } catch (ArchiveLimitException $e) { + $this->assertFileExists("$out/two.txt", $ext); + $this->assertFileNotExists("$out/three.txt", $ext); + } finally { + self::RDelete($out); + unlink($tmp); + } + } + } + + /** + * Extraction must stop before the entry that exceeds the file limit, skipped entries do not count + */ + public function testExtractionFileLimit() + { + foreach ($this->extensions as $ext) { + $tmp = sys_get_temp_dir() . '/phpa-limit-' . md5(uniqid('', true)) . '.' . $ext; + $out = sys_get_temp_dir() . '/phpa-limit-out-' . md5(uniqid('', true)); + $this->createLimitArchive($tmp); + + $tar = new Tar(); + $tar->setExtractionFileLimit(2); + $tar->open($tmp); + $this->assertCount(2, $tar->extract($out, '', '/one/'), $ext); + self::RDelete($out); + + $tar = new Tar(); + $tar->setExtractionFileLimit(2); + $tar->open($tmp); + try { + $tar->extract($out); + $this->fail("File limit was not enforced for $ext"); + } catch (ArchiveLimitException $e) { + $this->assertFileExists("$out/two.txt", $ext); + $this->assertFileNotExists("$out/three.txt", $ext); + } finally { + self::RDelete($out); + unlink($tmp); + } + } + } + /** * recursive rmdir()/unlink() * diff --git a/tests/ZipTestCase.php b/tests/ZipTestCase.php index 74478f5..f69a250 100644 --- a/tests/ZipTestCase.php +++ b/tests/ZipTestCase.php @@ -202,6 +202,85 @@ public function testLocalHeaderSizesIgnored() } } + /** + * Create a zip archive with three files of ten bytes each + * + * @param string $file the path to save the archive to + * @param int $level the compression level, 0 stores the files + */ + protected function createLimitArchive($file, $level) + { + $zip = new Zip(); + $zip->setCompression($level); + $zip->create($file); + $zip->addData('one.txt', str_repeat('1', 10)); + $zip->addData('two.txt', str_repeat('2', 10)); + $zip->addData('three.txt', str_repeat('3', 10)); + $zip->close(); + } + + /** + * Extraction must stop before the entry that exceeds the size limit + */ + public function testExtractionSizeLimit() + { + foreach (array(0, 9) as $level) { + $tmp = sys_get_temp_dir() . '/phpa-limit-' . md5(uniqid('', true)) . '.zip'; + $out = sys_get_temp_dir() . '/phpa-limit-out-' . md5(uniqid('', true)); + $this->createLimitArchive($tmp, $level); + + $zip = new Zip(); + $zip->setExtractionSizeLimit(30); + $zip->open($tmp); + $this->assertCount(3, $zip->extract($out), "level $level"); + self::RDelete($out); + + $zip = new Zip(); + $zip->setExtractionSizeLimit(25); + $zip->open($tmp); + try { + $zip->extract($out); + $this->fail("Size limit was not enforced for level $level"); + } catch (ArchiveLimitException $e) { + $this->assertFileExists("$out/two.txt", "level $level"); + $this->assertFileNotExists("$out/three.txt", "level $level"); + } finally { + self::RDelete($out); + @unlink($tmp); + } + } + } + + /** + * Extraction must stop before the entry that exceeds the file limit, skipped entries do not count + */ + public function testExtractionFileLimit() + { + $tmp = sys_get_temp_dir() . '/phpa-limit-' . md5(uniqid('', true)) . '.zip'; + $out = sys_get_temp_dir() . '/phpa-limit-out-' . md5(uniqid('', true)); + $this->createLimitArchive($tmp, 9); + + $zip = new Zip(); + $zip->setExtractionFileLimit(2); + $zip->open($tmp); + $this->assertCount(2, $zip->extract($out, '', '/one/')); + self::RDelete($out); + + $zip = new Zip(); + $zip->setExtractionFileLimit(2); + $zip->open($tmp); + try { + $zip->extract($out); + $this->fail('File limit was not enforced'); + } catch (ArchiveLimitException $e) { + $this->assertFileExists("$out/two.txt"); + $this->assertFileNotExists("$out/three.txt"); + } finally { + self::RDelete($out); + @unlink($tmp); + } + } + /** * A deflated entry shorter than its declared uncompressed size must be rejected. */ From d3c1f1bb82b5ea6a32c05958cf9fd1109c81f5f5 Mon Sep 17 00:00:00 2001 From: Andreas Gohr Date: Tue, 24 Nov 2026 18:13:06 +0000 Subject: [PATCH 3/7] Close the archive when extract() fails Zip::extract() and Tar::extract() closed the archive only after a successful extraction. After an exception, the file handle stayed open, and Windows refused to delete the archive. This made the extraction limit tests of 52eeb10 fail on Windows. The code that writes a single entry moved into extractEntry(), so extract() can close the archive in a finally block. Zip::extract() did not check that it could create the target directory. The first file then failed with an unclear error, and an empty archive gave no error at all. Both classes now use the same directory check for the target directory and for the directories of the entries, which throws an ArchiveIOException. --- src/Archive.php | 17 +++ src/Tar.php | 129 +++++++++--------- src/Zip.php | 298 ++++++++++++++++++++++-------------------- tests/TarTestCase.php | 21 +++ tests/ZipTestCase.php | 37 ++++++ 5 files changed, 300 insertions(+), 202 deletions(-) diff --git a/src/Archive.php b/src/Archive.php index 342ab6e..a55eab0 100644 --- a/src/Archive.php +++ b/src/Archive.php @@ -167,6 +167,23 @@ public function setExtractionFileLimit($files) $this->extractionFileLimit = (int) $files; } + /** + * Create a directory for extracted files, including missing parent directories + * + * @param string $directory the directory to create + * @return string the directory path without a trailing slash + * @throws ArchiveIOException when the directory cannot be created + */ + protected function createOutputDirectory($directory) + { + $directory = rtrim($directory, '/'); + @mkdir($directory, 0777, true); + if (!is_dir($directory)) { + throw new ArchiveIOException("Could not create directory '$directory'"); + } + return $directory; + } + /** * Check that extracting the next entry stays within the configured limits * diff --git a/src/Tar.php b/src/Tar.php index de8e1d6..c2c86e6 100644 --- a/src/Tar.php +++ b/src/Tar.php @@ -217,79 +217,45 @@ public function extract($outdir, $strip = '', $exclude = '', $include = '') throw new ArchiveIOException('Can not read from a closed archive'); } - $outdir = rtrim($outdir, '/'); - @mkdir($outdir, 0777, true); - if (!is_dir($outdir)) { - throw new ArchiveIOException("Could not create directory '$outdir'"); - } - $extracted = array(); $written = 0; - while ($dat = $this->readbytes(512)) { - // read the file header - $header = $this->parseHeader($dat); - if (!is_array($header)) { - continue; - } - $fileinfo = $this->header2fileinfo($header); - // apply strip rules - $fileinfo->strip($strip); + try { + $outdir = $this->createOutputDirectory($outdir); - // skip unwanted files - if (!strlen($fileinfo->getPath()) || !$fileinfo->matchExpression($include, $exclude)) { - $this->skipbytes(ceil($header['size'] / 512) * 512); - continue; - } - - if (!$fileinfo->getIsdir()) { - $written += $header['size']; - } - $this->checkExtractionLimits($fileinfo->getPath(), count($extracted) + 1, $written); + while ($dat = $this->readbytes(512)) { + // read the file header + $header = $this->parseHeader($dat); + if (!is_array($header)) { + continue; + } + $fileinfo = $this->header2fileinfo($header); - // create output directory - $output = $outdir.'/'.$fileinfo->getPath(); - $directory = ($fileinfo->getIsdir()) ? $output : dirname($output); - if (!file_exists($directory)) { - mkdir($directory, 0777, true); - } + // apply strip rules + $fileinfo->strip($strip); - // extract data - if (!$fileinfo->getIsdir()) { - $fp = @fopen($output, "wb"); - if (!$fp) { - throw new ArchiveIOException('Could not open file for writing: '.$output); + // skip unwanted files + if (!strlen($fileinfo->getPath()) || !$fileinfo->matchExpression($include, $exclude)) { + $this->skipbytes(ceil($header['size'] / 512) * 512); + continue; } - $size = $header['size']; - while ($size > 0) { - $read_size = min($size, 512); - $buffer = $this->readbytes(512); - if (strlen($buffer) < $read_size) { - fclose($fp); - @unlink($output); - throw new ArchiveCorruptedException( - 'Could not read the expected data for '.$header['filename'] - ); - } - fwrite($fp, $buffer, $read_size); - $size -= $read_size; + if (!$fileinfo->getIsdir()) { + $written += $header['size']; } + $this->checkExtractionLimits($fileinfo->getPath(), count($extracted) + 1, $written); - fclose($fp); - @touch($output, $fileinfo->getMtime()); - @chmod($output, $fileinfo->getMode()); - } else { - $this->skipbytes(ceil($header['size'] / 512) * 512); // the size is usually 0 for directories - } + $this->extractEntry($header, $fileinfo, $outdir.'/'.$fileinfo->getPath()); - if(is_callable($this->callback)) { - call_user_func($this->callback, $fileinfo); + if(is_callable($this->callback)) { + call_user_func($this->callback, $fileinfo); + } + $extracted[] = $fileinfo; } - $extracted[] = $fileinfo; + } finally { + $this->close(); } - $this->close(); return $extracted; } @@ -516,6 +482,51 @@ public function save($file) } } + /** + * Write the data of a single entry to disk + * + * Expects the read position at the start of the entry's data and moves it to the next header. + * + * @param array $header the parsed header of the entry + * @param FileInfo $fileinfo the entry with strip rules applied + * @param string $output the path to write the entry to + * @throws ArchiveIOException + * @throws ArchiveCorruptedException + */ + protected function extractEntry($header, $fileinfo, $output) + { + $this->createOutputDirectory(($fileinfo->getIsdir()) ? $output : dirname($output)); + + if ($fileinfo->getIsdir()) { + $this->skipbytes(ceil($header['size'] / 512) * 512); // the size is usually 0 for directories + return; + } + + $fp = @fopen($output, "wb"); + if (!$fp) { + throw new ArchiveIOException('Could not open file for writing: '.$output); + } + + $size = $header['size']; + while ($size > 0) { + $read_size = min($size, 512); + $buffer = $this->readbytes(512); + if (strlen($buffer) < $read_size) { + fclose($fp); + @unlink($output); + throw new ArchiveCorruptedException( + 'Could not read the expected data for '.$header['filename'] + ); + } + fwrite($fp, $buffer, $read_size); + $size -= $read_size; + } + + fclose($fp); + @touch($output, $fileinfo->getMtime()); + @chmod($output, $fileinfo->getMode()); + } + /** * Read from the open file pointer * diff --git a/src/Zip.php b/src/Zip.php index d27c854..c77ad3d 100644 --- a/src/Zip.php +++ b/src/Zip.php @@ -154,166 +154,51 @@ public function extract($outdir, $strip = '', $exclude = '', $include = '') throw new ArchiveIOException('Can not read from a closed archive'); } - $outdir = rtrim($outdir, '/'); - @mkdir($outdir, 0777, true); - $extracted = array(); $written = 0; - $cdir = $this->readCentralDir(); - $pos_entry = $cdir['offset']; // begin of the central file directory - - for ($i = 0; $i < $cdir['entries']; $i++) { - // read file header - @fseek($this->fh, $pos_entry); - $header = $this->readCentralFileHeader(); - $header['index'] = $i; - $pos_entry = ftell($this->fh); // position of the next file in central file directory - fseek($this->fh, $header['offset']); // seek to beginning of file header - $header = $this->readFileHeader($header); - $fileinfo = $this->header2fileinfo($header); - - // apply strip rules - $fileinfo->strip($strip); - - // skip unwanted files - if (!strlen($fileinfo->getPath()) || !$fileinfo->matchExpression($include, $exclude)) { - continue; - } + try { + $outdir = $this->createOutputDirectory($outdir); - // stored entries are copied as they are, all others are written with their uncompressed size - if (!$fileinfo->getIsdir()) { - $written += ($header['compression'] == 0) ? $header['compressed_size'] : $header['size']; - } - $this->checkExtractionLimits($fileinfo->getPath(), count($extracted) + 1, $written); + $cdir = $this->readCentralDir(); + $pos_entry = $cdir['offset']; // begin of the central file directory - $extracted[] = $fileinfo; + for ($i = 0; $i < $cdir['entries']; $i++) { + // read file header + @fseek($this->fh, $pos_entry); + $header = $this->readCentralFileHeader(); + $header['index'] = $i; + $pos_entry = ftell($this->fh); // position of the next file in central file directory + fseek($this->fh, $header['offset']); // seek to beginning of file header + $header = $this->readFileHeader($header); + $fileinfo = $this->header2fileinfo($header); - // create output directory - $output = $outdir.'/'.$fileinfo->getPath(); - $directory = ($header['folder']) ? $output : dirname($output); - @mkdir($directory, 0777, true); + // apply strip rules + $fileinfo->strip($strip); - // nothing more to do for directories - if ($fileinfo->getIsdir()) { - if(is_callable($this->callback)) { - call_user_func($this->callback, $fileinfo); + // skip unwanted files + if (!strlen($fileinfo->getPath()) || !$fileinfo->matchExpression($include, $exclude)) { + continue; } - continue; - } - - // entry data always lies before the central directory in a valid archive - if (ftell($this->fh) + $header['compressed_size'] > $cdir['offset']) { - throw new ArchiveCorruptedException( - 'Compressed data of '.$header['stored_filename'].' does not fit into the archive' - ); - } - - // only stored (0) and deflated (8) data can be extracted - if ($header['compression'] != 0 && $header['compression'] != 8) { - throw new ArchiveCorruptedException( - 'Compression method '.$header['compression'].' of '. - $header['stored_filename'].' is not supported' - ); - } - - // compressed files are written to temporary .gz file first - if ($header['compression'] == 0) { - $extractto = $output; - } else { - $extractto = $output.'.gz'; - } - // open file for writing - $fp = @fopen($extractto, "wb"); - if (!$fp) { - throw new ArchiveIOException('Could not open file for writing: '.$extractto); - } - - // prepend compression header - if ($header['compression'] != 0) { - $binary_data = pack( - 'va1a1Va1a1', - 0x8b1f, - chr($header['compression']), - chr(0x00), - time(), - chr(0x00), - chr(3) - ); - fwrite($fp, $binary_data, 10); - } - - // read the file and store it on disk - $size = $header['compressed_size']; - while ($size != 0) { - $read_size = ($size < 2048 ? $size : 2048); - $buffer = fread($this->fh, $read_size); - if ($buffer === false || strlen($buffer) !== $read_size) { - fclose($fp); - @unlink($extractto); - throw new ArchiveCorruptedException( - 'Could not read the expected data for '.$header['stored_filename'] - ); + // stored entries are copied as they are, all others are written with their uncompressed size + if (!$fileinfo->getIsdir()) { + $written += ($header['compression'] == 0) ? $header['compressed_size'] : $header['size']; } - fwrite($fp, $buffer, $read_size); - $size -= $read_size; - } + $this->checkExtractionLimits($fileinfo->getPath(), count($extracted) + 1, $written); - // finalize compressed file - if ($header['compression'] != 0) { - $binary_data = pack('VV', $header['crc'], $header['size']); - fwrite($fp, $binary_data, 8); - } + $extracted[] = $fileinfo; - // close file - fclose($fp); + $this->extractEntry($header, $fileinfo, $outdir.'/'.$fileinfo->getPath(), $cdir['offset']); - // unpack compressed file - if ($header['compression'] != 0) { - $gzp = @gzopen($extractto, 'rb'); - if (!$gzp) { - @unlink($extractto); - throw new ArchiveIOException('Failed file extracting. gzip support missing?'); - } - $fp = @fopen($output, 'wb'); - if (!$fp) { - throw new ArchiveIOException('Could not open file for writing: '.$extractto); - } - - $size = $header['size']; - while ($size != 0) { - $read_size = ($size < 2048 ? $size : 2048); - $buffer = gzread($gzp, $read_size); - $got = ($buffer === false) ? 0 : strlen($buffer); - if ($got === 0) { - fclose($fp); - gzclose($gzp); - @unlink($extractto); - @unlink($output); - throw new ArchiveCorruptedException( - $header['stored_filename'].' is smaller than its declared uncompressed size' - ); - } - @fwrite($fp, $buffer, $got); - $size -= $got; + if(is_callable($this->callback)) { + call_user_func($this->callback, $fileinfo); } - fclose($fp); - gzclose($gzp); - unlink($extractto); // remove temporary gz file - } - - @touch($output, $fileinfo->getMtime()); - if ($header['mode']) { - // only archives that stored a mode get one applied - @chmod($output, $header['mode'] & 07777); - } - if(is_callable($this->callback)) { - call_user_func($this->callback, $fileinfo); } + } finally { + $this->close(); } - $this->close(); return $extracted; } @@ -602,6 +487,133 @@ public function save($file) } } + /** + * Write the data of a single entry to disk + * + * Expects the file pointer at the start of the entry's data. + * + * @param array $header the merged central and local file header of the entry + * @param FileInfo $fileinfo the entry with strip rules applied + * @param string $output the path to write the entry to + * @param int $cdir_offset the position of the central directory, entry data must lie before it + * @throws ArchiveIOException + * @throws ArchiveCorruptedException + */ + protected function extractEntry($header, $fileinfo, $output, $cdir_offset) + { + $this->createOutputDirectory(($header['folder']) ? $output : dirname($output)); + if ($fileinfo->getIsdir()) { + return; + } + + // entry data always lies before the central directory in a valid archive + if (ftell($this->fh) + $header['compressed_size'] > $cdir_offset) { + throw new ArchiveCorruptedException( + 'Compressed data of '.$header['stored_filename'].' does not fit into the archive' + ); + } + + // only stored (0) and deflated (8) data can be extracted + if ($header['compression'] != 0 && $header['compression'] != 8) { + throw new ArchiveCorruptedException( + 'Compression method '.$header['compression'].' of '. + $header['stored_filename'].' is not supported' + ); + } + + // compressed files are written to temporary .gz file first + if ($header['compression'] == 0) { + $extractto = $output; + } else { + $extractto = $output.'.gz'; + } + + // open file for writing + $fp = @fopen($extractto, "wb"); + if (!$fp) { + throw new ArchiveIOException('Could not open file for writing: '.$extractto); + } + + // prepend compression header + if ($header['compression'] != 0) { + $binary_data = pack( + 'va1a1Va1a1', + 0x8b1f, + chr($header['compression']), + chr(0x00), + time(), + chr(0x00), + chr(3) + ); + fwrite($fp, $binary_data, 10); + } + + // read the file and store it on disk + $size = $header['compressed_size']; + while ($size != 0) { + $read_size = ($size < 2048 ? $size : 2048); + $buffer = fread($this->fh, $read_size); + if ($buffer === false || strlen($buffer) !== $read_size) { + fclose($fp); + @unlink($extractto); + throw new ArchiveCorruptedException( + 'Could not read the expected data for '.$header['stored_filename'] + ); + } + fwrite($fp, $buffer, $read_size); + $size -= $read_size; + } + + // finalize compressed file + if ($header['compression'] != 0) { + $binary_data = pack('VV', $header['crc'], $header['size']); + fwrite($fp, $binary_data, 8); + } + + // close file + fclose($fp); + + // unpack compressed file + if ($header['compression'] != 0) { + $gzp = @gzopen($extractto, 'rb'); + if (!$gzp) { + @unlink($extractto); + throw new ArchiveIOException('Failed file extracting. gzip support missing?'); + } + $fp = @fopen($output, 'wb'); + if (!$fp) { + throw new ArchiveIOException('Could not open file for writing: '.$extractto); + } + + $size = $header['size']; + while ($size != 0) { + $read_size = ($size < 2048 ? $size : 2048); + $buffer = gzread($gzp, $read_size); + $got = ($buffer === false) ? 0 : strlen($buffer); + if ($got === 0) { + fclose($fp); + gzclose($gzp); + @unlink($extractto); + @unlink($output); + throw new ArchiveCorruptedException( + $header['stored_filename'].' is smaller than its declared uncompressed size' + ); + } + @fwrite($fp, $buffer, $got); + $size -= $got; + } + fclose($fp); + gzclose($gzp); + unlink($extractto); // remove temporary gz file + } + + @touch($output, $fileinfo->getMtime()); + if ($header['mode']) { + // only archives that stored a mode get one applied + @chmod($output, $header['mode'] & 07777); + } + } + /** * Read a fixed number of bytes from the archive * diff --git a/tests/TarTestCase.php b/tests/TarTestCase.php index 24dbc35..805e4ef 100644 --- a/tests/TarTestCase.php +++ b/tests/TarTestCase.php @@ -1082,6 +1082,27 @@ public function testTruncatedEntryExtract() } } + /** + * A failed extraction must close the archive + */ + public function testExtractClosesArchiveOnException() + { + $dir = $this->getDir() . '/tar'; + $out = sys_get_temp_dir() . '/phpa-truncated-out-' . md5(uniqid('', true)); + + $tar = new Tar(); + $tar->open("$dir/truncated.tar"); + try { + $tar->extract($out); + } catch (ArchiveCorruptedException $e) { + $this->expectException(ArchiveIOException::class); + $this->expectExceptionMessage('Can not read from a closed archive'); + $tar->extract($out); + } finally { + self::RDelete($out); + } + } + /** * Skipping an excluded entry with less data than its declared size must stop at the end of the archive. */ diff --git a/tests/ZipTestCase.php b/tests/ZipTestCase.php index f69a250..ed8a90a 100644 --- a/tests/ZipTestCase.php +++ b/tests/ZipTestCase.php @@ -281,6 +281,29 @@ public function testExtractionFileLimit() } } + /** + * A failed extraction must close the archive + */ + public function testExtractClosesArchiveOnException() + { + $tmp = sys_get_temp_dir() . '/phpa-closed-' . md5(uniqid('', true)) . '.zip'; + $out = sys_get_temp_dir() . '/phpa-closed-out-' . md5(uniqid('', true)); + file_put_contents($tmp, $this->craftZip('tiny.txt', 'A', 0, 1048576, 1048576)); + + $zip = new Zip(); + $zip->open($tmp); + try { + $zip->extract($out); + } catch (ArchiveCorruptedException $e) { + $this->expectException(ArchiveIOException::class); + $this->expectExceptionMessage('Can not read from a closed archive'); + $zip->extract($out); + } finally { + self::RDelete($out); + unlink($tmp); + } + } + /** * A deflated entry shorter than its declared uncompressed size must be rejected. */ @@ -1080,6 +1103,20 @@ public function testZipExtractWithArchiveStreamIsClosed() $zip->extract($out); } + public function testZipExtractWithInvalidOutDir() + { + $this->expectException(ArchiveIOException::class); + $this->expectExceptionMessage('Could not create directory'); + $dir = $this->getDir() . '/zip'; + // Fails on Linux and Windows. + $out = '/root/invalid_out_dir:'; + + $zip = new Zip(); + + $zip->open("$dir/test.zip"); + $zip->extract($out); + } + /** * Extract the prebuilt zip files with component stripping * @depends testExtZipIsInstalled From 7467af254105f65a2d4f7cd40c02a1090a0a17a1 Mon Sep 17 00:00:00 2001 From: Andreas Gohr Date: Tue, 24 Nov 2026 18:13:15 +0000 Subject: [PATCH 4/7] Decompress ZIP entries without a temporary file Zip::extract() wrapped deflated data in a gzip header, wrote it to a temporary .gz file next to the output and decompressed that file with gzread(). This doubled the disk use, and a fatal error left the .gz file behind. The output size was only checked for a short result, and a wrong CRC was not detected. Deflated data is now decompressed in chunks with inflate_add() directly from the archive. Extraction fails when the output is larger or smaller than the declared size or when the CRC does not match. The data checks and the copying moved into checkEntryData() and copyEntryData(). --- src/Zip.php | 148 +++++++++++++++++++++--------------------- tests/ZipTestCase.php | 46 +++++++++++++ 2 files changed, 120 insertions(+), 74 deletions(-) diff --git a/src/Zip.php b/src/Zip.php index c77ad3d..6e88cb8 100644 --- a/src/Zip.php +++ b/src/Zip.php @@ -506,7 +506,39 @@ protected function extractEntry($header, $fileinfo, $output, $cdir_offset) return; } - // entry data always lies before the central directory in a valid archive + $this->checkEntryData($header, $cdir_offset); + + $fp = @fopen($output, 'wb'); + if (!$fp) { + throw new ArchiveIOException('Could not open file for writing: '.$output); + } + try { + $this->copyEntryData($header, $fp); + } catch (\Exception $e) { + fclose($fp); + @unlink($output); + throw $e; + } + fclose($fp); + + @touch($output, $fileinfo->getMtime()); + if ($header['mode']) { + // only archives that stored a mode get one applied + @chmod($output, $header['mode'] & 07777); + } + } + + /** + * Check that the data of an entry can be extracted + * + * Expects the file pointer at the start of the entry's data. + * + * @param array $header the merged central and local file header of the entry + * @param int $cdir_offset the position of the central directory, entry data must lie before it + * @throws ArchiveCorruptedException when the data lies outside the archive or uses an unsupported method + */ + protected function checkEntryData($header, $cdir_offset) + { if (ftell($this->fh) + $header['compressed_size'] > $cdir_offset) { throw new ArchiveCorruptedException( 'Compressed data of '.$header['stored_filename'].' does not fit into the archive' @@ -520,97 +552,65 @@ protected function extractEntry($header, $fileinfo, $output, $cdir_offset) $header['stored_filename'].' is not supported' ); } + } - // compressed files are written to temporary .gz file first - if ($header['compression'] == 0) { - $extractto = $output; - } else { - $extractto = $output.'.gz'; - } - - // open file for writing - $fp = @fopen($extractto, "wb"); - if (!$fp) { - throw new ArchiveIOException('Could not open file for writing: '.$extractto); - } - - // prepend compression header - if ($header['compression'] != 0) { - $binary_data = pack( - 'va1a1Va1a1', - 0x8b1f, - chr($header['compression']), - chr(0x00), - time(), - chr(0x00), - chr(3) - ); - fwrite($fp, $binary_data, 10); + /** + * Copy the data of an entry to a file, decompressing deflated data + * + * Expects the file pointer at the start of the entry's data. + * + * @param array $header the merged central and local file header of the entry + * @param resource $fp the file to write to + * @throws ArchiveIOException when zlib support is missing + * @throws ArchiveCorruptedException when the data does not match the declared size or CRC + */ + protected function copyEntryData($header, $fp) + { + $inflate = null; + if ($header['compression'] == 8) { + if (!function_exists('inflate_init')) { + throw new ArchiveIOException('Failed file extracting. zlib support missing?'); + } + $inflate = inflate_init(ZLIB_ENCODING_RAW); } - // read the file and store it on disk - $size = $header['compressed_size']; + $crc = hash_init('crc32b'); + $written = 0; + $size = $header['compressed_size']; while ($size != 0) { $read_size = ($size < 2048 ? $size : 2048); $buffer = fread($this->fh, $read_size); if ($buffer === false || strlen($buffer) !== $read_size) { - fclose($fp); - @unlink($extractto); throw new ArchiveCorruptedException( 'Could not read the expected data for '.$header['stored_filename'] ); } - fwrite($fp, $buffer, $read_size); $size -= $read_size; - } - - // finalize compressed file - if ($header['compression'] != 0) { - $binary_data = pack('VV', $header['crc'], $header['size']); - fwrite($fp, $binary_data, 8); - } - - // close file - fclose($fp); - // unpack compressed file - if ($header['compression'] != 0) { - $gzp = @gzopen($extractto, 'rb'); - if (!$gzp) { - @unlink($extractto); - throw new ArchiveIOException('Failed file extracting. gzip support missing?'); - } - $fp = @fopen($output, 'wb'); - if (!$fp) { - throw new ArchiveIOException('Could not open file for writing: '.$extractto); + if ($inflate) { + $buffer = @inflate_add($inflate, $buffer); + if ($buffer === false) { + throw new ArchiveCorruptedException('Could not decompress '.$header['stored_filename']); + } } - $size = $header['size']; - while ($size != 0) { - $read_size = ($size < 2048 ? $size : 2048); - $buffer = gzread($gzp, $read_size); - $got = ($buffer === false) ? 0 : strlen($buffer); - if ($got === 0) { - fclose($fp); - gzclose($gzp); - @unlink($extractto); - @unlink($output); - throw new ArchiveCorruptedException( - $header['stored_filename'].' is smaller than its declared uncompressed size' - ); - } - @fwrite($fp, $buffer, $got); - $size -= $got; + $written += strlen($buffer); + if ($written > $header['size']) { + throw new ArchiveCorruptedException( + $header['stored_filename'].' is larger than its declared uncompressed size' + ); } - fclose($fp); - gzclose($gzp); - unlink($extractto); // remove temporary gz file + hash_update($crc, $buffer); + fwrite($fp, $buffer); } - @touch($output, $fileinfo->getMtime()); - if ($header['mode']) { - // only archives that stored a mode get one applied - @chmod($output, $header['mode'] & 07777); + if ($written != $header['size']) { + throw new ArchiveCorruptedException( + $header['stored_filename'].' is smaller than its declared uncompressed size' + ); + } + if (hash_final($crc) !== sprintf('%08x', $header['crc'])) { + throw new ArchiveCorruptedException('CRC check failed for '.$header['stored_filename']); } } diff --git a/tests/ZipTestCase.php b/tests/ZipTestCase.php index ed8a90a..cddd32b 100644 --- a/tests/ZipTestCase.php +++ b/tests/ZipTestCase.php @@ -331,6 +331,52 @@ public function testCompressedEntrySmallerThanDeclaredSize() } } + /** + * Provide entries whose data does not match their headers + * + * @return array[] name, raw data, compression method, declared size and declared CRC + */ + public function provideBrokenEntryData() + { + $deflated = gzdeflate('hello world', 9); + + return array( + 'larger than declared' => array('large.txt', $deflated, 8, 5, crc32('hello world')), + 'wrong CRC of deflated data' => array('crc.txt', $deflated, 8, 11, 12345), + 'wrong CRC of stored data' => array('crc.txt', 'hello', 0, 5, 12345), + 'invalid deflate data' => array('invalid.txt', "\xff\xff\xff\xff", 8, 5, crc32('hello')), + ); + } + + /** + * Data that does not match the header must be rejected without leaving a file behind. + * + * @dataProvider provideBrokenEntryData + * @param string $name the file name of the entry + * @param string $data the raw file data of the entry + * @param int $compression the compression method to declare + * @param int $size the uncompressed size to declare + * @param int $crc the CRC32 checksum to declare + */ + public function testBrokenEntryData($name, $data, $compression, $size, $crc) + { + $tmp = sys_get_temp_dir() . '/phpa-broken-' . md5(uniqid('', true)) . '.zip'; + $out = sys_get_temp_dir() . '/phpa-broken-out-' . md5(uniqid('', true)); + file_put_contents($tmp, $this->craftZip($name, $data, $compression, strlen($data), $size, $crc)); + + $zip = new Zip(); + $zip->open($tmp); + try { + $zip->extract($out); + $this->fail('Extracting broken entry data did not fail'); + } catch (ArchiveCorruptedException $e) { + $this->assertFileNotExists("$out/$name"); + } finally { + self::RDelete($out); + unlink($tmp); + } + } + /** * An excluded entry is never read, so a broken header must not abort the extraction. */ From 950c0fd706249d24efd641509acd7cc724a5e054 Mon Sep 17 00:00:00 2001 From: Andreas Gohr Date: Tue, 24 Nov 2026 18:13:17 +0000 Subject: [PATCH 5/7] Check for write errors during extraction Zip::extract() and Tar::extract() ignored the result of fwrite(). When the disk was full, the extraction reported success and left truncated files. A failed write now throws an ArchiveIOException and removes the partial file. --- src/Tar.php | 31 ++++++++++++++++++------------- src/Zip.php | 6 ++++-- tests/TarTestCase.php | 23 +++++++++++++++++++++++ tests/ZipTestCase.php | 23 +++++++++++++++++++++++ 4 files changed, 68 insertions(+), 15 deletions(-) diff --git a/src/Tar.php b/src/Tar.php index c2c86e6..0b620f9 100644 --- a/src/Tar.php +++ b/src/Tar.php @@ -507,21 +507,26 @@ protected function extractEntry($header, $fileinfo, $output) throw new ArchiveIOException('Could not open file for writing: '.$output); } - $size = $header['size']; - while ($size > 0) { - $read_size = min($size, 512); - $buffer = $this->readbytes(512); - if (strlen($buffer) < $read_size) { - fclose($fp); - @unlink($output); - throw new ArchiveCorruptedException( - 'Could not read the expected data for '.$header['filename'] - ); + try { + $size = $header['size']; + while ($size > 0) { + $read_size = min($size, 512); + $buffer = $this->readbytes(512); + if (strlen($buffer) < $read_size) { + throw new ArchiveCorruptedException( + 'Could not read the expected data for '.$header['filename'] + ); + } + if (@fwrite($fp, $buffer, $read_size) !== $read_size) { + throw new ArchiveIOException('Could not write to file: '.$output); + } + $size -= $read_size; } - fwrite($fp, $buffer, $read_size); - $size -= $read_size; + } catch (\Exception $e) { + fclose($fp); + @unlink($output); + throw $e; } - fclose($fp); @touch($output, $fileinfo->getMtime()); @chmod($output, $fileinfo->getMode()); diff --git a/src/Zip.php b/src/Zip.php index 6e88cb8..6190a6e 100644 --- a/src/Zip.php +++ b/src/Zip.php @@ -561,7 +561,7 @@ protected function checkEntryData($header, $cdir_offset) * * @param array $header the merged central and local file header of the entry * @param resource $fp the file to write to - * @throws ArchiveIOException when zlib support is missing + * @throws ArchiveIOException when zlib support is missing or the file cannot be written * @throws ArchiveCorruptedException when the data does not match the declared size or CRC */ protected function copyEntryData($header, $fp) @@ -601,7 +601,9 @@ protected function copyEntryData($header, $fp) ); } hash_update($crc, $buffer); - fwrite($fp, $buffer); + if (@fwrite($fp, $buffer) !== strlen($buffer)) { + throw new ArchiveIOException('Could not write the data of '.$header['stored_filename']); + } } if ($written != $header['size']) { diff --git a/tests/TarTestCase.php b/tests/TarTestCase.php index 805e4ef..5ddefbb 100644 --- a/tests/TarTestCase.php +++ b/tests/TarTestCase.php @@ -1213,6 +1213,29 @@ public function testExtractionFileLimit() } } + /** + * A failed write must abort the extraction and remove the partial file + */ + public function testExtractToFullDisk() + { + $tmp = sys_get_temp_dir() . '/phpa-full-' . md5(uniqid('', true)) . '.tar'; + $out = vfsStream::url('home_root_path/out'); + $this->createLimitArchive($tmp); + vfsStream::setQuota(15); + + $tar = new Tar(); + $tar->open($tmp); + try { + $tar->extract($out); + $this->fail('Extracting to a full disk did not fail'); + } catch (ArchiveIOException $e) { + $this->assertStringEqualsFile("$out/one.txt", str_repeat('1', 10)); + $this->assertFileNotExists("$out/two.txt"); + } finally { + unlink($tmp); + } + } + /** * recursive rmdir()/unlink() * diff --git a/tests/ZipTestCase.php b/tests/ZipTestCase.php index cddd32b..cc1347b 100644 --- a/tests/ZipTestCase.php +++ b/tests/ZipTestCase.php @@ -281,6 +281,29 @@ public function testExtractionFileLimit() } } + /** + * A failed write must abort the extraction and remove the partial file + */ + public function testExtractToFullDisk() + { + $tmp = sys_get_temp_dir() . '/phpa-full-' . md5(uniqid('', true)) . '.zip'; + $out = vfsStream::url('home_root_path/out'); + $this->createLimitArchive($tmp, 9); + vfsStream::setQuota(15); + + $zip = new Zip(); + $zip->open($tmp); + try { + $zip->extract($out); + $this->fail('Extracting to a full disk did not fail'); + } catch (ArchiveIOException $e) { + $this->assertStringEqualsFile("$out/one.txt", str_repeat('1', 10)); + $this->assertFileNotExists("$out/two.txt"); + } finally { + unlink($tmp); + } + } + /** * A failed extraction must close the archive */ From 10a9e40d00a42f4d10e80cd2b4bfd76a6b44f05e Mon Sep 17 00:00:00 2001 From: Andreas Gohr Date: Tue, 24 Nov 2026 18:36:59 +0000 Subject: [PATCH 6/7] Count all data read from Tar archives toward the size limit The size limit of Tar::extract() counted only the extracted files. Skipped entries, empty blocks and pax metadata were still decompressed in full. An 854 byte .tar.bz2 with a skipped 1 GB entry took 2.3 s, and a 785 byte .tar.bz2 of zero blocks took 3.4 s, without reaching any limit. Tar::extract() now applies the size limit to all data it reads from the uncompressed archive. Skipping an entry beyond the limit fails before the data is decompressed. Tar::skipbytes() did not advance the read position for bzip2 archives, because it counted the skipped bytes down to zero before it added them. --- src/Archive.php | 3 ++- src/Tar.php | 27 +++++++++++++++++++- tests/TarTestCase.php | 59 ++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 84 insertions(+), 5 deletions(-) diff --git a/src/Archive.php b/src/Archive.php index a55eab0..3e2a7be 100644 --- a/src/Archive.php +++ b/src/Archive.php @@ -144,7 +144,8 @@ public function setCallback($callback) * Set the maximum total size of all files written by extract() * * The extraction is aborted with an ArchiveLimitException before an entry would exceed the limit. Files - * extracted up to that point are not removed. + * extracted up to that point are not removed. For Tar archives, the limit also applies to all data read from the + * uncompressed archive, including headers and skipped entries. * * @param int $bytes the maximum number of bytes, 0 for no limit */ diff --git a/src/Tar.php b/src/Tar.php index 0b620f9..a4b042c 100644 --- a/src/Tar.php +++ b/src/Tar.php @@ -55,6 +55,9 @@ class Tar extends Archive protected $skipUntil = 0; protected $paxGlobal = array(); + /** @var int maximum position extract() may read to in the uncompressed archive, 0 for no limit */ + protected $readLimit = 0; + /** * Sets the compression to use * @@ -221,6 +224,7 @@ public function extract($outdir, $strip = '', $exclude = '', $include = '') $written = 0; try { + $this->readLimit = $this->extractionSizeLimit; $outdir = $this->createOutputDirectory($outdir); while ($dat = $this->readbytes(512)) { @@ -253,6 +257,7 @@ public function extract($outdir, $strip = '', $exclude = '', $include = '') $extracted[] = $fileinfo; } } finally { + $this->readLimit = 0; $this->close(); } @@ -537,6 +542,7 @@ protected function extractEntry($header, $fileinfo, $output) * * @param int $length bytes to read * @return string + * @throws ArchiveLimitException */ protected function readbytes($length) { @@ -548,6 +554,7 @@ protected function readbytes($length) $ret = @fread($this->fh, $length); } $this->position += strlen($ret); + $this->checkReadLimit($this->position); return $ret; } @@ -582,9 +589,13 @@ protected function writebytes($data) * This is basically a wrapper around seek() (and a workaround for bzip2) * * @param int $bytes seek to this position + * @throws ArchiveLimitException */ protected function skipbytes($bytes) { + $this->checkReadLimit($this->position + $bytes); + $this->position += $bytes; + if ($this->comptype === Archive::COMPRESS_GZIP) { @gzseek($this->fh, $bytes, SEEK_CUR); } elseif ($this->comptype === Archive::COMPRESS_BZIP) { @@ -600,7 +611,21 @@ protected function skipbytes($bytes) } else { @fseek($this->fh, $bytes, SEEK_CUR); } - $this->position += $bytes; + } + + /** + * Check that extract() stays within its size limit when reading up to the given position + * + * @param int $position the position in the uncompressed archive + * @throws ArchiveLimitException + */ + protected function checkReadLimit($position) + { + if ($this->readLimit && $position > $this->readLimit) { + throw new ArchiveLimitException( + 'Reading the archive exceeds the limit of '.$this->readLimit.' bytes' + ); + } } /** diff --git a/tests/TarTestCase.php b/tests/TarTestCase.php index 5ddefbb..15ac34f 100644 --- a/tests/TarTestCase.php +++ b/tests/TarTestCase.php @@ -1150,7 +1150,7 @@ protected function createLimitArchive($file) } /** - * Extraction must stop before the entry that exceeds the size limit + * Extraction must stop when reading the archive exceeds the size limit */ public function testExtractionSizeLimit() { @@ -1159,14 +1159,16 @@ public function testExtractionSizeLimit() $out = sys_get_temp_dir() . '/phpa-limit-out-' . md5(uniqid('', true)); $this->createLimitArchive($tmp); + // three header and data blocks plus two end blocks $tar = new Tar(); - $tar->setExtractionSizeLimit(30); + $tar->setExtractionSizeLimit(4096); $tar->open($tmp); $this->assertCount(3, $tar->extract($out), $ext); self::RDelete($out); + // ends after the header of the third file $tar = new Tar(); - $tar->setExtractionSizeLimit(25); + $tar->setExtractionSizeLimit(2560); $tar->open($tmp); try { $tar->extract($out); @@ -1181,6 +1183,57 @@ public function testExtractionSizeLimit() } } + /** + * Provide archive data that is read but never extracted + * + * @return array[] the uncompressed archive data and the exclude expression + */ + public function provideUnextractedData() + { + $dir = $this->getDir() . '/tar'; + return array( + 'skipped entry' => array(file_get_contents("$dir/truncated.tar"), '/truncated/'), + 'zero blocks' => array(str_repeat("\0", 1048576), ''), + ); + } + + /** + * Data that is read but never extracted must count toward the size limit + * + * @dataProvider provideUnextractedData + * @param string $data the uncompressed archive data + * @param string $exclude a regular expression of files to exclude + */ + public function testExtractionSizeLimitCountsUnextractedData($data, $exclude) + { + $archives = array('tar' => $data); + if (extension_loaded('zlib')) { + $archives['tgz'] = gzencode($data); + } + if (extension_loaded('bz2')) { + $archives['tbz'] = bzcompress($data); + } + + foreach ($archives as $ext => $content) { + $tmp = sys_get_temp_dir() . '/phpa-unextracted-' . md5(uniqid('', true)) . '.' . $ext; + $out = sys_get_temp_dir() . '/phpa-unextracted-out-' . md5(uniqid('', true)); + file_put_contents($tmp, $content); + + $tar = new Tar(); + $tar->setExtractionSizeLimit(65536); + $tar->open($tmp); + try { + $tar->extract($out, '', $exclude); + $this->fail("Size limit was not enforced for $ext"); + } catch (ArchiveLimitException $e) { + $this->assertStringContainsString('Reading the archive exceeds', $e->getMessage(), $ext); + } finally { + self::RDelete($out); + unlink($tmp); + } + } + } + /** * Extraction must stop before the entry that exceeds the file limit, skipped entries do not count */ From 2d20061e978913f46310caccc0e9ee60ed727b38 Mon Sep 17 00:00:00 2001 From: Andreas Gohr Date: Tue, 24 Nov 2026 18:36:59 +0000 Subject: [PATCH 7/7] Document the extraction limits in the README --- README.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/README.md b/README.md index 9702461..5882adc 100644 --- a/README.md +++ b/README.md @@ -79,3 +79,24 @@ Tar archives have no field for that. Names are written exactly as you pass them stored. Anything written by a current tool uses UTF-8, but an older archive may use any encoding without saying so, and such names are returned unchanged. Use ```mb_check_encoding()``` if you need to know, and convert them yourself if you know what encoding they use. + +Extracting untrusted archives +----------------------------- + +A small archive can expand to a very large size or to very many files. By default, ```extract()``` has no limits. +Set limits before you extract archives from an untrusted source: + +```php +$zip = new Zip(); +$zip->setExtractionSizeLimit(100 * 1024 * 1024); // bytes of all extracted files +$zip->setExtractionFileLimit(1000); // number of extracted files and directories +$zip->open('upload.zip'); +$zip->extract('/tmp/upload'); +``` + +Before each entry, ```extract()``` compares the size declared in the archive with the limit. When an entry would +exceed a limit, it throws an ArchiveLimitException. Files extracted up to that point stay on disk. + +For Tar archives, the size limit also applies to all data that ```extract()``` reads from the uncompressed archive, +including headers and skipped entries. Since Tar needs to decompress the file as a whole, this is the only way to +limit the time to decompress a Tar archive.