I check fileupload magicCheck before uploading.
Scenario 1 :- I change my .exe file to .pdf when I Upload that file I am getting error message that is (Correct)
Scenario 1 :- I upload same file and change the request before uploading from tool (burpSuit) change its mime type .exe file(MZ) to the magic number .pdf file (%PDF-) and forward that request it will Upload how to restrict that.
C#
protected void Save(object sender, EventArgs e)
{
string filePath = fileUpload.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
Stream checkStream = fileUpload.PostedFile.InputStream;
BinaryReader chkBinary = new BinaryReader(checkStream);
Byte[] chkbytes = chkBinary.ReadBytes(0x10);
string data_as_hex = BitConverter.ToString(chkbytes);
string magicCheck = data_as_hex.Substring(0, 11);
//Set the contenttype based on File Extension
switch (magicCheck)
{
case "FF-D8-FF-E1": contenttype = "image/jpg";
break;
case "FF-D8-FF-E0": contenttype = "image/jpeg";
break;
case "25-50-44-46": contenttype = "text/pdf";
break;
}
if (contenttype != String.Empty)
{
Byte[] bytes = chkBinary.ReadBytes((Int32)checkStream.Length);
lblMessage.Text = "Uploaded File is of type " + contenttype;
lblMessage.ForeColor = System.Drawing.Color.Green;
}
else
{
lblMessage.Text = "Please Upload Valid File with Original extension";
lblMessage.ForeColor = System.Drawing.Color.Red;
}
}