Last active
November 16, 2024 02:35
-
-
Save righettod/e50d2c4b5e6e28b002cafe2c0fa40f5e to your computer and use it in GitHub Desktop.
Function to validate that a ZIP file do not contains "ZIP SLIP" payload entries.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Function to validate that a ZIP file do not contains "ZIP SLIP" payload entries. | |
* @param string $zipFilePath Path to the ZIP to test. | |
* @return bool TRUE only if the archive do not contains ZIP SLIP payload entries. | |
* @link https://snyk.io/research/zip-slip-vulnerability | |
* @link https://stackoverflow.com/a/3599093/451455 (inspired from) | |
*/ | |
function isZipValid($zipFilePath){ | |
$isValid = false; | |
$invalidEntryCount = 0; | |
try { | |
$zip = zip_open($zipFilePath); | |
if ($zip) | |
{ | |
while ($zipEntry = zip_read($zip)) | |
{ | |
$completeName = zip_entry_name($zipEntry); | |
//See https://www.php.net/manual/en/function.strpos.php | |
if(strpos($completeName, "..") !== false){ | |
$invalidEntryCount++; | |
}else{ | |
//Handle case of symlink, read the first 1KB of the entry and check them. | |
//This check is prone to bypass if the payload is over the first 1KB so | |
//feel free to apply this check on the entire content of the entry. | |
$content = zip_entry_read($zipEntry, 1024); | |
$finfo = new finfo(FILEINFO_MIME); | |
$mimeFull = $finfo->buffer($content); | |
$mime = trim(explode(";",$mimeFull)[0]); | |
if($mime === "text/plain" && strpos($content, "..") !== false){ | |
$invalidEntryCount++; | |
} | |
} | |
} | |
$isValid = ($invalidEntryCount === 0); | |
} | |
} catch (Exception $e) { | |
$isValid = false; | |
//Log error | |
} | |
return $isValid; | |
} | |
//Call example | |
if(isZipValid("temp.zip")) { echo("IS VALID"); } else { echo("IS INVALID"); } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Execution example: