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. diff --git a/src/Archive.php b/src/Archive.php index 45c87fd..3e2a7be 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,71 @@ 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. 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 + */ + 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; + } + + /** + * 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 + * + * @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); - if (!is_array($header)) { - continue; - } - $fileinfo = $this->header2fileinfo($header); + $written = 0; - // apply strip rules - $fileinfo->strip($strip); + try { + $this->readLimit = $this->extractionSizeLimit; + $outdir = $this->createOutputDirectory($outdir); - // skip unwanted files - if (!strlen($fileinfo->getPath()) || !$fileinfo->matchExpression($include, $exclude)) { - $this->skipbytes(ceil($header['size'] / 512) * 512); - continue; - } + 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 = 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); + 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->readLimit = 0; + $this->close(); } - $this->close(); return $extracted; } @@ -502,11 +487,62 @@ 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); + } + + 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; + } + } catch (\Exception $e) { + fclose($fp); + @unlink($output); + throw $e; + } + fclose($fp); + @touch($output, $fileinfo->getMtime()); + @chmod($output, $fileinfo->getMode()); + } + /** * Read from the open file pointer * * @param int $length bytes to read * @return string + * @throws ArchiveLimitException */ protected function readbytes($length) { @@ -518,6 +554,7 @@ protected function readbytes($length) $ret = @fread($this->fh, $length); } $this->position += strlen($ret); + $this->checkReadLimit($this->position); return $ret; } @@ -552,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) { @@ -562,13 +603,29 @@ 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 { @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/src/Zip.php b/src/Zip.php index 641544c..6190a6e 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 = '') @@ -153,159 +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(); - - $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; - } - - $extracted[] = $fileinfo; - - // create output directory - $output = $outdir.'/'.$fileinfo->getPath(); - $directory = ($header['folder']) ? $output : dirname($output); - @mkdir($directory, 0777, true); - - // nothing more to do for directories - if ($fileinfo->getIsdir()) { - if(is_callable($this->callback)) { - call_user_func($this->callback, $fileinfo); + $written = 0; + + try { + $outdir = $this->createOutputDirectory($outdir); + + $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; } - 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; } @@ -594,6 +487,135 @@ 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; + } + + $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' + ); + } + + // 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' + ); + } + } + + /** + * 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 or the file cannot be written + * @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); + } + + $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) { + throw new ArchiveCorruptedException( + 'Could not read the expected data for '.$header['stored_filename'] + ); + } + $size -= $read_size; + + if ($inflate) { + $buffer = @inflate_add($inflate, $buffer); + if ($buffer === false) { + throw new ArchiveCorruptedException('Could not decompress '.$header['stored_filename']); + } + } + + $written += strlen($buffer); + if ($written > $header['size']) { + throw new ArchiveCorruptedException( + $header['stored_filename'].' is larger than its declared uncompressed size' + ); + } + hash_update($crc, $buffer); + if (@fwrite($fp, $buffer) !== strlen($buffer)) { + throw new ArchiveIOException('Could not write the data of '.$header['stored_filename']); + } + } + + 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']); + } + } + /** * Read a fixed number of bytes from the archive * @@ -774,16 +796,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..15ac34f 100644 --- a/tests/TarTestCase.php +++ b/tests/TarTestCase.php @@ -1062,6 +1062,233 @@ 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); + } + } + + /** + * 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. + */ + 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); + } + } + } + + /** + * 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 when reading the archive 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); + + // three header and data blocks plus two end blocks + $tar = new Tar(); + $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(2560); + $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); + } + } + } + + /** + * 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 + */ + 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); + } + } + } + + /** + * 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 31b23a3..cc1347b 100644 --- a/tests/ZipTestCase.php +++ b/tests/ZipTestCase.php @@ -176,6 +176,157 @@ 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); + } + } + + /** + * 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 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 + */ + 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. */ @@ -203,6 +354,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. */ @@ -975,6 +1172,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 diff --git a/tests/tar/truncated.tar b/tests/tar/truncated.tar new file mode 100644 index 0000000..4a0d543 Binary files /dev/null and b/tests/tar/truncated.tar differ