3

User uploaded images account for a large portion of the content on the site I'm working on. I tried storing them outside of the webroot and fetching them with readfile() for security reasons, but it was just too slow so I had to go back to the old method.

Now I'm looking to make sure all uploads are 100% sanitized since they'll be stored inside the webroot. My question is, if a user were to rename a harmful script to a .jpg, .gif, .png, or .bmp and uploaded it, would it still be harmful when executed or fetched if the image was recreated with a function like this:

function imageCreateFromAny($filepath) { 
    $type = exif_imagetype($filepath); // [] if you don't have exif you could use getImageSize() 
    $allowedTypes = array( 
        1,  // [] gif 
        2,  // [] jpg 
        3,  // [] png 
        6   // [] bmp 
    ); 
    if (!in_array($type, $allowedTypes)) { 
        return false; 
    } 
    switch ($type) { 
        case 1 : 
            $im = imageCreateFromGif($filepath); 
        break; 
        case 2 : 
            $im = imageCreateFromJpeg($filepath); 
        break; 
        case 3 : 
            $im = imageCreateFromPng($filepath); 
        break; 
        case 6 : 
            $im = imageCreateFromBmp($filepath); 
        break; 
    }    
    return $im;  
} 

In other words, is there anyway to trick one of the imagecreatefrom* functions into executing content as a script instead of an image or would even a harmful script that's been run through this be reduced to a broken image?

miken32
  • 42,008
  • 16
  • 111
  • 154
SISYN
  • 2,209
  • 5
  • 24
  • 45
  • I don't think so, but I am not qualified. As far as I know scripts can be stored in the meta data of jpeg files, but *I don't think* that `imagecreatefrom...` uses the meta data. renaming a bad file to a PNG or other format is very probably not an issue but files should be checked with the `finfo` set of functions, I read on Information Security Stack exchange they're much more fool proof than others (such as getimagesize). – Martin Mar 06 '16 at 18:45
  • Thank you for your comment, hoping someone else can weigh in on this. – SISYN Mar 07 '16 at 02:10
  • Perhaps try the same question over at Information Security Stack exchange – Martin Mar 07 '16 at 12:10
  • Thanks, I asked the question on there as well. Hopefully someone can chime in on one of them. http://security.stackexchange.com/questions/116707/recreating-uploads-linked-images-with-imagecreatefrom-php – SISYN Mar 07 '16 at 14:09

0 Answers0