如何检查文件是否仅是特定类型. [英] How to check if the file is of specific type only.

查看:71
本文介绍了如何检查文件是否仅是特定类型.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想允许上传.xls,.txt文件.但是,恶意用户可以将可执行文件扩展名从.exe更改为.xls(或.txt)并上传.
如何检查并限制用户免受此类攻击?
VB.NET或C#中是否有可用的类或方法?

I want to allow uploading of .xls,.txt files. However a malicious user could change an executable file extension from .exe to .xls (or .txt) and upload it.
How to check and restrict the user from such attack?
Is there any class or method available in VB.NET or C#?

推荐答案

由于它来自另一方,因此您不能依赖mime类型或文件扩展名-你提到自己了.
嗅探数据流以确定其内容类型并不容易.它依赖于文件签名知识库,在此进行描述: http://www.garykessler.net/library/file_sigs.html [^ ]

urlmon.dll中有一个FindMimeFromData()函数,但这是非托管代码,因此您需要PInvoke,请参阅:魔术数字 [
这可能对您也很有趣:
小型内容检测库 [ ^ ]
As it comes from another party you can not rely on mime types, or file extension - as you mentioned yourself.
Sniffing a data stream to determine it''s content type is not easy. It relies on the file signature knowledge base, described here: http://www.garykessler.net/library/file_sigs.html[^]

There is a FindMimeFromData() function in the urlmon.dll, but that is unmanaged code, thus you need PInvoke, see: http://www.dotnet247.com/247reference/msgs/26/133278.aspx[^]. It has it''s limitations, it can detect only 26 mime types. In linux there is an implementation called "magic numbers[^]".

This might be also interesting for you: A small Content Detection Library[^]


您可以通过仅检查前两个字节来直接检查文件是否为exe.使用有效的文件路径调用IsExe方法将使您知道是否为exe.如果隐藏了exe(例如,带有其他一些扩展名txt,zip,xls等),这将起作用.
You directly check the file is an exe or not by just examining the first two bytes. Call the method IsExe with valid file path will let you know is an exe or not. This will work if hidden exe(ie with some other extension txt, zip, xls etc)
byte[] EXE_SIGNATURE = {77, 90 };
private byte[] ReadTwoBytes(string filepath)
{
    try
    {
        using (FileStream fsSource = new FileStream(filepath, FileMode.Open, FileAccess.Read))
        {

            // Read two bytes from source file into a byte array.
            byte[] bytes = new byte[2];
            int n = fsSource.Read(bytes, 0, 2);
            return bytes;
        }
    }
    catch
    {

        return (byte[])null;
    }
}
//check exe signature
private bool IsExe(string filePath)
{
    byte[] b = ReadTwoBytes(filePath);
    return b.SequenceEqual(EXE_SIGNATURE);
}


嗨...使用此代码只需将代码放在按钮click


hi...use this simply put this code on button click


Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
       Label2.Visible = True
       Dim filePath As String = FileUpload1.PostedFile.FileName
       Dim filename1 As String = Path.GetFileName(filePath)
       Dim ext As String = Path.GetExtension(filename1)
       Dim type As String = [String].Empty

       If FileUpload1.HasFile Then

           Try


               Select Case ext
                   Case ".xls"

                       type = "application/vnd.ms-excel"

                       Exit Select

                   Case ".txt"
                       type = "application/vnd.txt"

                       Exit Select

               End Select

               If type <> [String].Empty Then
                   connection()
                   Dim fs As Stream = FileUpload1.PostedFile.InputStream
                   Dim br As New BinaryReader(fs)
                   Dim bytes As [Byte]() = br.ReadBytes(CType(fs.Length, Int32))
                   query = "insert into Excelfiledemo(Name,type,data)" & " values (@Name, @type, @Data)"
                   com = New SqlCommand(query, con)
                   com.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename1
                   com.Parameters.Add("@type", SqlDbType.VarChar).Value = type
                   com.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes
                   com.ExecuteNonQuery()
                   Label2.ForeColor = System.Drawing.Color.Green

                   Label2.Text = "File Uploaded Successfully"
               Else
                   Label2.ForeColor = System.Drawing.Color.Red


                   Label2.Text = "Select Only Excel and text Files "
               End If
           Catch ex As Exception


               Label2.Text = "Error: " & ex.Message.ToString()

           End Try
       End If
   End Sub




希望对您有帮助...




i hope this helps you...


这篇关于如何检查文件是否仅是特定类型.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆