AlfaProject has asked for the wisdom of the Perl Monks concerning the following question:

Hello What is best way to validate an image upload? Prevent from uploaded images to run with chmod or there is a way to check if file is not an image when uploading? Thanks a lot.

Replies are listed 'Best First'.
Re: Image uploading
by Corion (Patriarch) on Mar 20, 2011 at 21:21 UTC

    See Image::Size. Also, of course, setting +r and only +r is the appropriate permission for "uploaded images" (or rather, any user content). You certainly almost never want to be executing "uploaded content". Also consider running jpegtrans or any other resizer over the content, force-resizing it to discard all metadata etc. from the image.

Re: Image uploading
by rastoboy (Monk) on Mar 21, 2011 at 00:14 UTC
    I know this doesn't directly answer your question, but I think it's more important to observe that you will have better luck keeping your applications secure with a "default-deny" mindset, which I think is one of the most important concepts in computer security.

    For example, you seem to be chasing down all the possible bad stuff people could do with your script, and acting against them. This is known as "enumerating badness", and is generally acknowledged as an impossible task.

    Instead, it is much better to write your code in such a way that all images are uploaded without execute permissions, for example, since they don't need them, and therefore it makes sense to "deny by default". And then you don't have to worry about people executing them.

    Or, instead of finding out if a file is an image when uploading, "deny by default" execution permissions for any uploaded file, and add them later if a specific set of conditions is met (although I can't imagine letting random stuff uploaded to be executed is ever a good idea).

    So it's better to allow *only* the stuff you want to allow, than to try to deny every single bad thing that could happen.

    I do hope that helps.