Search code examples
phpwordpresszipunzip

Security of unzipping user submitted files


Not so much of a coding problem here, but a general question relating to security. I'm currently working on a project that allows user submitted content. A key part of this content is the user uploads a Zip file. The zip file should contain only mp3 files.

I then unzip those files to a directory on the server, so that we can stream the audio on the website for users to listen to.

My concern is that this opens us up for some potentially damaging zip files. I've read about 'zipbombs' in the past, and obviously don't want a malicious zip file causing damage.

So, is there a safe way of doing this? Can i scan the zip file without unzipping it first, and if it contains anything other than MP3's delete it or flag a warning to the admin?

If it makes a difference i'm developing the site on Wordpress. I currently use the built in upload features of wordpress to let the user upload the zip file to our server (i'm not sure if there's any form of security within wordpress already to scan the zip file?)


Solution

  • Code, only extract MP3s from zip, ignore everthing else

    $zip = new ZipArchive();
    $filename = 'newzip.zip';
    
    if ($zip->open($filename)!==TRUE) {
       exit("cannot open <$filename>\n");
    }
    
    for ($i=0; $i<$zip->numFiles;$i++) {
       $info = $zip->statIndex($i);
       $file = pathinfo($info['name']);
       if(strtolower($file['extension']) == "mp3") {
            file_put_contents(basename($info['name']), $zip->getFromIndex($i));
       }
    
    }
    $zip->close();
    

    I would use use something like id3_get_version (http://www.php.net/manual/en/function.id3-get-version.php) to ensure the contents of the file is mp3 too