jk's blog

Testing for Hack Scripts, Scan Your Uploads

This was ripped from a patch I made to ZenCart to deal with malicious uploads. It was stripped from a class, and it should probably be worked into pretty much any uploader class. (The class is in upload.php)

It doesn’t handle binary files, but it’s good with scripts. It’s fast, so you don’t suffer the performance hit of a real virus scan.

function looks_like_script() {
    $score = 0;
    if (preg_match('/.+(.php|.PHP|.pl|.PL|.cgi|.CGI)$/', 
       $this->filename)) $score++;

    $fh = fopen($this->file['tmp_name'],'r'); //this is the temp file
    $line = fgets($fh,6);
    if ('<?'==substr($line,0,2)) $score++;
    if ('#!'==substr($line,0,2)) $score++;

    if ($score > 0) return true;
    else return false;

To use it, call it from within the class like this:

 if ($this->looks_like_script()) exit;

Basically, if the file looks like a script exit silently. This isn’t as good as something that actually unwinds the current action and throws an error message. That would be harder to implement. This just satisfies the goal of preventing someone from uploading a script to your website.