Prevent an exe from being uploaded even after rena

2019-09-06 09:15发布

I am working on asp.net with c#.

There is a file upload control in my form. Everything is working fine.

The problem is that an .exe file can be uploaded by just renaming it. I would also like to restrict the size.

1条回答
孤傲高冷的网名
2楼-- · 2019-09-06 09:35

best way in your case is check the first bytes of the file to determine what they are.

you should use FindMimeFromData function to determines the MIME type from the data provided.

Have a look at this file signatures table

and at this SO answer that shows you how get mime type without using extension.

Here there is a table with List of file signatures

exe files have hex signature 4D 5A (In ASCII representation, 0x5A4D is MZ)

signature of exe file

from this point we can do this function

    public static bool IsExecutable(string filePath)
    {            
      var firstBytes = new byte[2];
      using (var fileStream = File.Open(filePath, FileMode.Open))
      {
          fileStream.Read(firstBytes, 0, 2);
      }
      return Encoding.UTF8.GetString(firstBytes) == "MZ";
    }
查看更多
登录 后发表回答