How to tell if a posted file is really an image
This is a useful method to determine if a file posted for upload (via HTTP) is actually an image. This was created in .net 1.1 but also works in 2.0 without any modifications.
Heres a bit of background. Anyone can change the content type of a file before posting it. Its as simple as changing an extension of a file to something your looking for. So if someone wanted to upload a malicious program or file they could simply change the extension to an images extension (in this case) and upload something that .net initially thinks is an image but really is not.
All this method does is read the first 64 bytes of data from the posted file and compares the data in the header to determine if its an image. It takes a byte array as an input and returns either true or false to the calling method.
Thats really all there is to it. Once this is in place you can actually add more if statements to look for more image types (like .tiff, etc). The reason we dont use a switch statement for this is because for different image formats the "identifying byte(s)" are located in different index positions. So to add more images you will have to dig around the net a bit finding out about what header bytes identify different images.
hope this helps someone out,
mcm.
Heres a bit of background. Anyone can change the content type of a file before posting it. Its as simple as changing an extension of a file to something your looking for. So if someone wanted to upload a malicious program or file they could simply change the extension to an images extension (in this case) and upload something that .net initially thinks is an image but really is not.
All this method does is read the first 64 bytes of data from the posted file and compares the data in the header to determine if its an image. It takes a byte array as an input and returns either true or false to the calling method.
public bool IsImage(byte[] data)
{
//read 64 bytes of the stream only to determine the type
string myStr = System.Text.Encoding.ASCII.GetString(data).Substring(0, 16);
//check if its definately an image.
if (myStr.Substring(8, 2).ToString().ToLower() != "if")
{
//its not a jpeg
if (myStr.Substring(0, 3).ToString().ToLower() != "gif")
{
//its not a gif
if (myStr.Substring(0, 2).ToString().ToLower() != "bm")
{
//its not a .bmp
if (myStr.Substring(0, 2).ToString().ToLower() != "ii")
{
myStr = null;
return false;
}
}
}
}
myStr = null;
return true;
}
Thats really all there is to it. Once this is in place you can actually add more if statements to look for more image types (like .tiff, etc). The reason we dont use a switch statement for this is because for different image formats the "identifying byte(s)" are located in different index positions. So to add more images you will have to dig around the net a bit finding out about what header bytes identify different images.
hope this helps someone out,
mcm.
0 Comments:
Post a Comment
<< Home