r/PHPhelp • • May 05 '17

Accepting user supplied image uploads - am I doing anything wrong?

Basically, I want users to be able to share and upload images. So I've concocted this as a first attempt to to make sure they're not sending anything harmful. I'll step through it, but for reference, I put the whole thing on Pastebin ** EDIT That's the original file - the newest version is Here**:

First, we accept the file and copy it to /home/myapp/uploads. To be clear, the app is served from /home/myapp/public/, so the initial file upload is not in a path that can be accessed by the outside world. We also give it a random name, which is the SHA1 hash of the file, and the current file extension.

$upload     = $_FILES['file']['tmp_name'];
$fileName   = $_FILES['file']['name'];
$ext        = pathinfo($fileName, PATHINFO_EXTENSION);

$uploadPath   = '/home/myapp/uploads/';   // Initial directory image is sent to

// move uploaded file to uploads directory
$hash = sha1_file($upload);
$newfile = $hash . "." . $ext;
move_uploaded_file($upload, $uploadPath . $newfile);

Now, we want to make sure that the files we received were actually images.

// Validate the file we received - step one
$imageSize  = getimagesize($uploadPath . $newfile);

if($imageSize == false) {
    echo "Not an image";
    exit();
}

In the config file elsewhere, MAX_IMAGE_SIZE is set to 500, which is the largest dimension (in pixels) a final image should have. If it's larger than 500pixels per side, it should be scaled down proportionately. Note that even if the image is less than 500 pixels per side, we still want to resize it at 100% just to rewrite the file and strip out anything bad (hopefully).

$imageWidth  = $imageSize[0];
$imageHeight = $imageSize[1];
$imageType   = $imageSize['mime'];

if($imageWidth < MAX_IMAGE_SIZE && $imageWidth < MAX_IMAGE_SIZE) {
    $percentage = 1;
} elseif ($imageWidth > $imageHeight) {
    $percentage = (MAX_IMAGE_SIZE / $imageWidth);
} else {
    $percentage = (MAX_IMAGE_SIZE/ $imageHeight);
}

$newHeight  = round($imageHeight * $percentage, 0);
$newWidth   = round($imageWidth  * $percentage, 0);

Now, rather than looking at the extension, we look at the mime type of the image and figure out how to create an image out of it. At this point, we only accept GIF, JPEG and PNG's

// create image
switch($imageType)
{
    case 'image/jpeg':
        $img = @imagecreatefromjpeg($uploadPath . $newfile);
        break;
    case 'image/gif':
        $img = @imagecreatefromgif($uploadPath . $newfile);
        break;
    case 'image/png':
        $img = @imagecreatefrompng($uploadPath . $newfile);
        break;
    default:
        echo "not a supported image type";
        exit();
        break;
}

$destImage = imagecreatetruecolor($newWidth, $newHeight);

imagecopyresampled($destImage, $img, 0, 0, 0, 0, $newWidth, $newHeight, $imageWidth, $imageHeight);

After we've created a new image in memory, we copy it to the publicly accessible directory ('images/uploads'), keeping the previous SHA1 hash as the file name, adding the dimensions of the new image, and saving it as a JPEG regardless of the original format.

imagejpeg($destImage, 'images/uploads/' . $hash . "-" . $newWidth . "x" . $newHeight . ".jpg");

echo json_encode("Uploaded " . $newfile);

At this point, I could delete the original uploads, but am thinking about holding on to them so that a user could request to download the original full-size image if they wanted. I've also read about the imagedestroy() functions, but my understanding is that the memory is released as soon as the script exits, which is immediately after writing the final JPEG.

So that's what I have right now. I feel like this can be refactored into a class at some point, with methods like:

-saveOriginal
-getImageSize
-scaleImage
-saveFinalImage

Of course, once I was 99% of the way through this, it dawned on me that I should have checked https://packagist.org, but being that this is my first time trying to manipulate images in PHP, I thought it was a good learning experience.

Anyways, looking for feedback. Anything I'm missing? Anything that's redundant? Anything that could be done better? Or just do general cleanup and refactoring (i don't like my variable names, for instance).

Any thoughts would be greatly appreciated! Thanks

9 Upvotes

11 comments sorted by

4

u/colshrapnel May 05 '17

Looks good though I've some minor objections

  1. You may want to perpend getimagesize with @ as it have a regretful habit of throwing a warning for the incorrect images.

  2. It's not a very good idea to convert all images to jpeg. Some will lose the quality considerably. Why not to keep the format?

  3. Looks like you don't need the original extension at all thus

     $upload     = $_FILES['file']['tmp_name'];
     $uploadPath   = '/home/myapp/uploads/'; 
     $newfile = sha1_file($upload);

should be enough

2

u/[deleted] May 05 '17

OK!

I updated it here: https://pastebin.com/UrXrE6g8

1 - Easy enough with the @, I had done this with the @imagecreate*'s as I'd seen recommendations to do so on stack overflow and elsewhere. Just felt wrong, I've also seen lots of people complaining that their scripts don't work, while they're suppressing errors at the same time! :)

2 - I could preserve PNG's in their original format as well. I guess my worry is if I got a GIF with an 8-bit color palette, what would happen when it got resized? I know, I should experiment and see what happens :)

3 - Dropped the extension variable per your recommendation, as you're correct, it served no purpose since i'm evaluating mime types.

4 - I also delete (unlink) images that fail any of the validations (getimagesize or wrong mime type), so every file that is in uploads has a matching resampled file in public/images/uploads.

thank you!

1

u/[deleted] May 06 '17

Taking the combined input from /u/colshrapnel and /u/peacepudding, here's where I'm at so far:

Pastebin Link

A few constants that aren't defined in the file:

APPPATH -  this is just the root directory of the app
APP_KEY - This is just a random string - previously, if a malicious user uploaded code, it would be named as the SHA1 hash of the file, which is something they would know. Now it's saved as a hash of the hash of the file plus the APP_KEY, just to make it harder for them to predict where a file might end up.
MAX_IMAGE_SIZE - this is the max pixel dimensions.

Also, as /u/peacepudding mentioned, no longer moving the Temp File until validation has passed. Which means I don't need to unlink files that don't pass validation anymore.

I also renamed variables so be a little more descriptive without being overly verbose. Added a few more comments along the way. Echo unique errors at different places where validation fails so we know where something broke, and added checks to insure that a few operations didn't fail (move_uploaded_file, imagecopyresampled, and imagejpeg).

Also tested:

JPEG file processes correctly.

PNG file processes correctly.

TIF file gets rejected for being an unsupported image.

PDF and PHP files gets rejected for not being an image at all.

.sh file renamed to .jpg also gets rejected for not being an image.

** Anything else I'm missing? Thanks! **

1

u/[deleted] May 06 '17

I'm also not sure what the impact of HUGE files would be. Right now i'm only protected by PHP's upload-max-filesize.

I created a 20,000 x 20,000 pixel RGB JPEG, all white, saved at minimal quality which has a file size of 4.3 MB, but uncompresses to 1.12 GB in memory to test.

  1. It got rejected for invalid dimensions. I think that's because I check if one side is large than the other, but not if its a perfect square! Fixed that.

  2. Looks like my VM with 768 MB is in a lot of pain right now! http://imgur.com/a/1pwod

Will update whenever this process finishes... but its making me think, I need to check this before proceeding and set a sane max image size to even begin processing a file.

1

u/[deleted] May 06 '17

Well it looks like it finished, but it did not create a file at the end of the process.

Makes me wonder how other services handle this, but I don't want to get in trouble with IMgur or anyone else by seeing if or how their servers handle that file!

1

u/[deleted] May 06 '17

Remedied that by checking dimensions before resampling:

if($imageHeight > MAX_IMAGE_SIZE_IN_PIXELS || $imageWidth > MAX_IMAGE_SIZE_IN_PIXELS) {
    echo "the image is too large! aborting....";
    exit();
}

Of course a 5000px by 10px image (as that's what I set MAX_IMAGE_SIZE_IN_PIXELS to) wouldn't pose a problem, so I'm thinking I could actually change this to check the total number of pixels in the image rather than checking a single dimension.

3

u/[deleted] May 06 '17

Its a decent start, but personally I would do ALL validation before calling move_uploaded_file(), and use that point as the threshold for when an image upload is valid and sanitised.

You say you are ignoring the file extension, but the user supplied extension is actually dictating the destination filename....

$newfile = $hash . "." . $ext;

I know you sanitise it further after that, but lets say $ext evaluated to 'php'

There could theoretically be a brief period where the image could be requested via its full path, and the web server would execute it as a php script.

This would require some misconfiguration, and maybe not possible right now, but why risk it?

Just change your imagecreatefrom* calls to read directly from the upload directory

Also if the image results in 0 width or height, just reject it instantly, rather than carrying on and doing your resizing then validating that. Basically, take every measure to reject the upload at the earliest possible opportunity.

2

u/colshrapnel May 06 '17

/u/dbbeginner, that's actuelly a very good suggestion. why bother with moving the file around and making a dedicated directory if you already have a file at your disposal?

1

u/demunted May 06 '17

There are people smarter than me on here but I'm wondering about validating the file before even trying to process it by checking it on the server side. Unsure about your input scanning but I do know that just checking extensions is not enough.

Edit I see you are using getimagesize and I don't know if that's safe. Maybe someone else can chime in.

1

u/doitstuart May 06 '17

Seems like a good place to ask this question.

Is it possible to spoof the mime type in the file header? If so, how would that compromise security? Is there a workaround.

1

u/colshrapnel May 06 '17

The better place is your own question for sure, as it could be interesting to others as well. So I'd ask you to post it as the new question in this sub. But in short - yes, it's easily spoofed. No workarounds are really required though as the real mime type is rather insignificant. Just make sure that the file ext is from the expected range.