开发者

Restrict file types allowed for upload asp.net

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 attacker 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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜