zoukankan      html  css  js  c++  java
  • 图片上传安全性问题,根据ContentType (MIME) 判断其实不准确、不安全

    图片上传常用的类型判断方法有这么几种---截取扩展名、获取文件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 = new byte[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,png
        if (fileTypeStr.Contains(fileFlag))
        {
            file0.SaveAs(Server.MapPath("~/" + file0.FileName));
        }
        else
        {
            Response.Write("图片格式不正确:" + fileFlag);
        }
    }
  • 相关阅读:
    marginleft IE Firefox 浏览器下的不同
    提取HTML代码中文字的C#函数
    分享按钮汇总
    jquery UI集合
    向用户授予对象特权
    oracle中使用聚合函数
    创建对象类型
    jdk1.6.0_01配置系统环境变量
    修改表
    将一个实体映射到多张数据库表
  • 原文地址:https://www.cnblogs.com/hsw-2013/p/4693711.html
Copyright © 2011-2022 走看看