Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
74 changes: 74 additions & 0 deletions src/Archive.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down Expand Up @@ -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 = '');
Expand Down Expand Up @@ -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'
);
}
}
}
10 changes: 10 additions & 0 deletions src/ArchiveLimitException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace splitbrain\PHPArchive;

/**
* The extraction exceeds a configured limit
*/
class ArchiveLimitException extends \Exception
{
}
155 changes: 106 additions & 49 deletions src/Tar.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down Expand Up @@ -208,6 +211,7 @@ public function readCurrentEntry($length = PHP_INT_MAX)
* @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 = '')
Expand All @@ -216,66 +220,47 @@ 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();
while ($dat = $this->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;
}

Expand Down Expand Up @@ -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)
{
Expand All @@ -518,6 +554,7 @@ protected function readbytes($length)
$ret = @fread($this->fh, $length);
}
$this->position += strlen($ret);
$this->checkReadLimit($this->position);
return $ret;
}

Expand Down Expand Up @@ -552,23 +589,43 @@ 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) {
// there is no seek in bzip2, we simply read on
// 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'
);
}
}

/**
Expand Down
Loading
Loading