Click here to Skip to main content
15,885,182 members
Please Sign up or sign in to vote.
3.63/5 (5 votes)
See more:
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#?
Posted
Updated 17-Sep-12 22:15pm
v4
Comments
Andrei Straut 18-Sep-12 4:07am    
Try googling "C# FileUpload".

Question downvoted for lack of any apparent attempt to document yourself about your own problem

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[^]
 
Share this answer
 
Comments
Kuthuparakkal 18-Sep-12 4:45am    
Plz check my solution...
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)
C#
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);
}
 
Share this answer
 
v2
Comments
Zoltán Zörgő 18-Sep-12 4:50am    
Could be good, if this simple blacklisting is enough. If whitelisting is needed, than you can not avoid the magic numbers, or something alike. But still, my5 !
Kuthuparakkal 18-Sep-12 4:58am    
thanks! Zoltan
hi...use this simply put this code on button click


VB
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...
 
Share this answer
 
v2
Comments
Er. Tushar Srivastava 18-Sep-12 4:49am    
I guess the user requires to read file header to know the exact type of file even if it's extension has been changed so as to protect some malicious content to be uploaded on the server.... Please review the question...
vishal_h 21-Sep-12 8:07am    
Yes Tushar
Er. Tushar Srivastava 21-Sep-12 8:25am    
Then, will this code work?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900