Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image upload validation in .NET

I've got a page where the user can upload an image which is later saved on the server. I'm doing simple validation of the uploaded file by checking its extension (.jpg, .png, etc.)

Is such validation enough for server security? Or does this leave the opportunity for someone to upload malicious code which can harm my server? If it is possible to validate the uploaded images, how it can be done?

like image 830
Burjua Avatar asked May 09 '26 18:05

Burjua


2 Answers

Whenever end users put anything on your server, there is a chance for malicious behavior. While it's unlikely that double clicking on a .jpg image will hork your box, stranger things have been known to happen. (For example, who knew PDFs could contain so many security problems!)

Your best bet is to try actually loading the image and seeing if it the GDI+ libraries recognize it as a valid image. If you don't get a runtime exception, then you know that the image is 'valid'. This however won't protect you in the case that loading the image in GDI+ doesn't hork your box in the first place.

You can further protect yourself by loading the image in a separate AppDomain, but at narrows down the potential threats.

like image 111
Chris Smith Avatar answered May 11 '26 08:05

Chris Smith


You can generally read/check the MIME type of the file, by using the urlmon.dll. See this excellent answer here.

It's also not a bad idea to have a good anti virus program installed on your server. Enable the real time file system scanning and when the file is gone a moment after it was uploaded it contained most likely malicious code.

like image 22
Martin Buberl Avatar answered May 11 '26 08:05

Martin Buberl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!