很多时候木马程序会伪装成其他格式的文件上传到网站,最常见的如图片格式。
本文就以C #为例讲述C#判断上传文件是否是图片以防止木马上传的方法,具体方法如下:
方法一:用image对象判断是否为图片
?
1 2 3 4 5 6 7 8 9
10
11
12
13
14
15
16
17 /// <summary>
/// 判断文件是否为图片
/// </summary>
/// <param name="path">文件的完整路径</param> /// <returns>返回结果</returns>
public Boolean IsImage(string path)
{
try
{
System.Drawing.Image img =
System.Drawing.Image.FromFile(path);
return true;
}
catch(Exception e)
{
return false;
}
}
方法二,判断文件头?
1 2 3 4 5 6 7 8 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 /// <summary>
/// 根据文件头判断上传的文件类型
/// </summary>
/// <param name="filePath">filePath是文件的完整路径 </param>
/// <returns>返回true或false</returns>
private bool IsPicture(string filePath)
{
try
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(fs);
string fileClass;
byte buffer;
buffer = reader.ReadByte();
fileClass = buffer.ToString();
buffer = reader.ReadByte();
fileClass += buffer.ToString();
reader.Close();
fs.Close();
if(fileClass == "255216"|| fileClass == "7173"|| fileClass == "13780"|| fileClass == "6677")
//255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
25
26
27
28
29
30
31
32
33
34 {
return true; }
else
{
return false; }
}
catch
{
return false; }
}
测试显示方法二针对常规修改的木马有效,也就是直接修改扩展名的,比如把.asp改成.jpg 这种。
但是对于那种用工具生成的jpg木马则没有效果。
此时推荐大家使用第一种方法。