Prevent an exe from being uploaded even after renaming its extention

走远了吗. 提交于 2019-12-13 07:25:24

问题


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


来源:https://stackoverflow.com/questions/25031190/prevent-an-exe-from-being-uploaded-even-after-renaming-its-extention

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!