Validating User Uploaded images

Discussion in 'PHP' started by NoamBarz, Jul 29, 2008.

  1. #1
    When building an application that uses images uploaded from users, one of the most important issues is making sure the uploaded file is a valid image file and that it does not contain hidden scripts inside it that could be harmful.

    I was wondering whether anyone knew of the best way to secure image file uploads.

    One way would be to check the file type through the files array provided by php: $_FILES['userfile']['type']. However, it is clearly stated that this is not reliable.

    Another way would be to check the file extension. This too will not do the trick, b/c executable php files can be masked as image files with appropriate extensions such as gif or jpg.

    Developers sometimes think that validating an image using the php getimagesize function will do the trick. This method too will not work b/c executable php code can be inserted into the image description causing the image to pass the getimagesize validation while still containing harmful code. I'd just mention that in this respect, that the attacker must be able to find the uploaded file in order to use it. Changing the image file name is therefore a must, if one wants to be protected against such attacks.

    So it seems like none of these methods alone will do. Actually, it doesn't seem like using all of them will completely secure your application.

    I was wondering whether someone knew of better ways to secure image file uploads. This is a common feature and I am sure there are many methods of securing this process. Please share your thoughs.
     
    NoamBarz, Jul 29, 2008 IP
  2. EricBruggema

    EricBruggema Well-Known Member

    Messages:
    1,740
    Likes Received:
    28
    Best Answers:
    13
    Trophy Points:
    175
    #2
    getimagesize is indeed the best available option, and ofcource naming the files with a NON executable extension.
     
    EricBruggema, Jul 30, 2008 IP
  3. yleiko

    yleiko Peon

    Messages:
    74
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Some server side software can be used that checks a file and returns whether it is an image file or not.
     
    yleiko, Jul 30, 2008 IP
  4. zerxer

    zerxer Peon

    Messages:
    368
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Hmm.. For my sites, I always check the extension and do the appropriate ImageCreateFrom___ function based on the extension and see if it returns false or not (never thought of just running getimagesize). I don't really know what else you could do if people can still get passed these checks with other methods..
     
    zerxer, Jul 30, 2008 IP
  5. PET

    PET Member

    Messages:
    86
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    43
    #5
    I usualy checked the extention and the mime type.
     
    PET, Jul 30, 2008 IP