views:

71

answers:

2

Hi,

I want to limit the allowed uploaded file types to images, pdfs, and docs. What is the recommended way to approach this?

I assume checking the file extension alone is not enough, since an attacked can change the file extension as he wishes.

I also thought about checking against MIME Type using PostedFile.ContentType.

I still don't know if this is adding any further functionality than checking against file extensions alone, and if an attacker have and ability to change this information easily.

This is basically for a course management system for students to upload assignments and teachers to download and view them.

Thanks.

A: 

I agree with validating the extension as show by pranay_stacker, and checking against PostedFile.ContentType will provide another layer of security. But, it still relies on a the Content-Type header set by the client and therefore susceptible to attack.

If you want to guarantee the file types then you need to upload the file and check the first 2 bytes. Something along the lines of (untested)

string fileclass = "";
using(System.IO.BinaryReader r = new System.IO.BinaryReader(fileUpload1.PostedFile.InputStream))
{
    byte buffer = r.ReadByte();
    fileclass = buffer.ToString();
    buffer = r.ReadByte();
    fileclass += buffer.ToString();
    r.Close();
}
if(fileclass!="3780")//.pdf 208207=.doc 7173=.gif 255216=.jpg 6677=.bmp 13780=.png
{
    errorLiteral.Text = "<p>Error - The upload file must be in PDF format.</p>"
    return;
}

This is very rough and not robust, hopefully someone can expand on this.

Luke
Thanks!! This is good enough to get me started! el.pescado's post bellow got me wondering if this solution is cross platform compatible i.e. do different OS generate different file headers for the same format. Your thoughts?In addition - what are the costs-benefits of such an approach (well benefits are obvious)? Keep in mind that this is for a course management system where students upload files and teachers download them (or vice versa).Maybe this entire approach is overkill?
Eran
If this is not a publicly available system then I think you're right, this approach is overkill. If you can trust the students not have the intent to purposely upload malicious files then extension and content type validation would be sufficient.
Luke
A: 

To be 99% sure, you'll have to check magic numbers of a uploaded files, just like UNIX file utility does.

el.pescado
Thanks! This is a similar direction to what Luke offered in his post above. Is reading the the first two bytes enough to obtain the information I need for the magic numbers? Is this a platform independent solution?
Eran
It depends on file type. See linked Wikipedia article for some examples.
el.pescado