Is HttpPostedFile.ContentType a flawless way to validate an uploaded file?

I want to validate the file type to make sure the user is uploading an image of type JPEG, GIF, or PNG. Instead of checking the file extension, I figured using HttpPostedFile.ContentType would be safer since it checks the MIME content type.

protected void cvValidateImageType_ServerValidate(object source, ServerValidateEventArgs args)
{
    if (fupImage.HasFile)
    {
        args.IsValid = (fupImage.PostedFile.ContentType.ToLower() == "image/jpg" ||
                        fupImage.PostedFile.ContentType.ToLower() == "image/jpeg" ||
                        fupImage.PostedFile.ContentType.ToLower() == "image/pjpeg" ||
                        fupImage.PostedFile.ContentType.ToLower() == "image/gif" ||
                        fupImage.PostedFile.ContentType.ToLower() == "image/x-png" ||
                        fupImage.PostedFile.ContentType.ToLower() == "image/png");

    }
    else
        args.IsValid = true;
}

Is this a flawless way to check the file type, or can it be fooled?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Using the extension is probably safer. The ContentType is sent in the http request from the client. If you test for the extension, the user can change the extension of an exe to jpg, but it won’t run as an exe.

Method 2

Both using the extension and the HTTP headers are equally unreliable, as they both can be faked with ease, either by a malicious attacker using raw HTTP requests, or by an innocent browser user picking an incorrectly named file. If you want to be certain, you must crack the file open and analyze the content, there is no other way.

Method 3

To reliably know the content type, you might want to look into Content Type sniffing, for instance:

http://suika.fam.cx/www/markup/html/whatpm/Whatpm/ContentType.html

This tries to determine the content type of the file by examining the first few bytes.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x