Prevent an exe from being uploaded even after rena

2019-09-06 08:53发布

问题:

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:

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)

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";
    }