当前位置: 移动技术网 > IT编程>开发语言>c# > http图片上传安全性问题 根据ContentType (MIME) 判断其实不准确、不安全

http图片上传安全性问题 根据ContentType (MIME) 判断其实不准确、不安全

2019年07月18日  | 移动技术网IT编程  | 我要评论

图片上传常用的类型判断方法有这么几种---截取扩展名、获取文件contenttype (mime) 、读取byte来判断(这个什么叫法来着?)。前两种都有安全问题。容易被上传不安全的文件,如木马什么的。第1种截取文件扩展名来判断的方法很明显不安 全,第2种contenttype mime可以伪造,所以用contenttype来判断其实也不安全。建议采用第3种。

c#演示:

1.截取扩展名来做判断,不可取。

if (request.files.count > 0)
{
  //这里只测试上传第一张图片file[0]
  httppostedfile file0 = request.files[0];
  string ext = file0.filename.substring(file0.filename.lastindexof('.') + 1);//文件扩展名string[] filetypestr = { "jpg", "gif", "bmp", "png" };
  if (filetypestr.contains(ext))
  {
    file0.saveas(server.mappath("~/" + file0.filename));//保存文件  }
  else
  {
    response.write("图片格式不正确" + ext);
  }
}

2.判断contenttype (mime) ,比第1种方案安全。但其实contenttype是可伪造的,所以也不够安全。

if (request.files.count > 0)
{
//这里只测试上传第一张图片file[0]
  httppostedfile file0 = request.files[0];
  string contenttype = file0.contenttype;//文件类型string[] filetypestr = { "image/gif","image/x-png","image/pjpeg","image/jpeg","image/bmp"};
  if (filetypestr.contains(contenttype))
  {
    file0.saveas(server.mappath("~/" + file0.filename));
  }
  else
  {
    response.write("图片格式不正确" + contenttype);
  }
}

3.通过byte获取文件类型,来做判断。

if (request.files.count > 0)
{
//这里只测试上传第一张图片file[0]
  httppostedfile file0 = request.files[0];
  //转换成byte,读取图片mime类型  stream stream;
  //int contentlength = file0.contentlength; //文件长度byte[] filebyte = newbyte[2];//contentlength,这里我们只读取文件长度的前两位用于判断就好了,这样速度比较快,剩下的也用不到。
  stream = file0.inputstream;
  stream.read(filebyte, 0, 2);//contentlength,还是取前两位  stream.close();
  string fileflag = "";
  if (filebyte != null && filebyte.length > 0)//图片数据是否为空  {
    fileflag = filebyte[0].tostring() + filebyte[1].tostring();         
  }
  string[] filetypestr = { "255216", "7173", "6677", "13780" };//对应的图片格式jpg,gif,bmp,pngif (filetypestr.contains(fileflag))
  {
    file0.saveas(server.mappath("~/" + file0.filename));
  }
  else
  {
    response.write("图片格式不正确:" + fileflag);
  }
}

以上内容就是本文给大家叙述的http图片上传安全性问题 根据contenttype (mime) 判断其实不准确、不安全,希望大家喜欢。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网