As suggested on my StackOverflow question, I am now directing this towards the Information Security group, since no one was able to answer my question despite multiple up-votes.
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?
Update I will also be checking file types and extensions, but I wanted to know if the user managed to bypass those, would this last resort help in protecting my server and/or clients in any way. Thank you.
imagecreatefrompng
can relatively easily be compromised to contain PHP. So..... I think the perogative is to usefinfo
(NOTexif_
) and confirm file is pure PNG (or whatever type) , although I'm not even sure that that helps, because it comes down to the fact that the image file is a genuine image file but contains some unwanted extras, and functions to check if a file is a genuine file can't realistically check for all possible unwanted extras, :-/finfo
can also be bypassed (at least under certain circumstances, see the link in my answer).cat evil.PHP >> image.PNG ; file image.PNG ; php image.PNG