Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP image upload security approach

I develop a php script to replace a current one, that will have a lot of exposure to various markets/countries. This script between others offers an photo upload functionality .

After a lot of reading about the issue, I followed the approach described below. I would deeply appreciate your comments on its security.

  1. The photo is uploaded in a private 777 folder outside web root.
  2. A check for white listed extensions is performed (allow only jpgs, gifs, pngs) everything else is deleted.
  3. Use of getimagesize to check of min-max dimensions and photo validity.
  4. Check of mimetype and file extension match.
  5. Resizing of uploaded photo to std dimensions (using imagecopyresampled).
  6. Saving the created files as jpg.
  7. Removal of original file.
  8. Save photos with a new (not random name) ie img51244.jpg.
  9. Move the new photos to variable subdirectories of a public folder (777 permissions) according to a non predictable algorithm. I.e., img10000.jpg will be stored at photos/a/f/0/img10000.jpg while img10001.jpg will be stored at photos/0/9/3/img10001.jpg. This is done for other reasons (use of subdomains for static content serve or use of a CDN).

The script will run on a linux dedicated server.

like image 983
Alex Avatar asked Sep 06 '11 08:09

Alex


People also ask

Is PHP file upload safe?

To upload files in PHP is easy and secure. I would recommend learning about: pathinfo - Returns information about a file path.

What danger is there in allowing uploads over the web?

Upload forms on web pages can be dangerous because they allow attackers to upload malicious code to the web server. Attackers can then use tricks to execute this code and access sensitive information or even take control of the server.


1 Answers

  1. A directory with chmod 0777 is, by definition, public to other users logged into your server, not private. The correct permissions would be 700 and being owned by apache (or whatever user your webserver runs at). I'm not sure why you wouldn't use php's default temporary directory here, since it tends to be outside of the web root too.
  2. A white-list is a good idea. Be careful to have a correct implementation. For example, the regexp /.png/ actually matches apng.php.
  3. This step is a great idea. It basically checks the file magic.
  4. Is not strictly necessary. In the two previous steps, we have determined that extension and file format are correct. If you require a correct MIME type to be specified by the client, you should also check that the given MIME type and the one determined above are equivalent.

Steps 5 to 8 are not security-related.

Step 9: I'm assuming that your site allows everyone to see every photo. If that isn't the case, you should have a URL scheme with substantially longer URLs (say, the hashsum of the image).

like image 112
phihag Avatar answered Nov 16 '22 04:11

phihag