Is HttpPostedFile.ContentType a perfect way to verify the downloaded file?

I want to check the file type to make sure the user uploads an image like JPEG, GIF or PNG. Instead of checking the file extension, I realized that using HttpPostedFile.ContentType would be more secure, as it checks the type of MIME content.

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 perfect way to check the file type, or can it be tricked?

+7
c # validation image
source share
3 answers

Using the extension is probably safer. ContentType is sent in an HTTP request from the client. If you are testing the extension, the user can change the exe extension to jpg, but it will not work as exe.

+6
source

Both uses of HTTP extensions and headers are equally unreliable, as both can be easily tricked by either an attacker using raw HTTP requests or an innocent browser user who selects an incorrectly named file. If you want to be sure, you have to hack the file open and analyze the content, there will be no other way.

+4
source

To reliably know the type of content, you may need to examine the sniffing Type Type, for example:

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

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

0
source

All Articles