web常见攻击六——文件上传漏洞

 

文件上传漏洞就是对用户上传的文件类型判断不完善,导致攻击者上传非法类型的文件,从而对网站进行攻击。

以上传图片为例进行介绍,下面来看初级的程序。

<?php
if (isset($_POST['Upload'])) { 

$target_path = DVWA_WEB_PAGE_TO_ROOT."hackable/uploads/";
$target_path = $target_path . basename( $_FILES['uploaded']['name']);

if(!move_uploaded_file($_FILES['uploaded']['tmp_name'], $target_path)) {

    echo '';
    echo 'Your image was not uploaded.';
    echo '';

} else {

    echo '';
    echo $target_path . ' succesfully uploaded!';
    echo '';

}

}
?>

这段程序没有对图片类型及大小进行任何判断,就对文件进行上传,很容易产生文件攻击。

下面这段程序对文件大小及类型进行验证

<?php
if (isset($_POST['Upload'])) {

$target_path = DVWA_WEB_PAGE_TO_ROOT."hackable/uploads/";
$target_path = $target_path . basename($_FILES['uploaded']['name']);
$uploaded_name = $_FILES['uploaded']['name'];
$uploaded_type = $_FILES['uploaded']['type'];
$uploaded_size = $_FILES['uploaded']['size'];

if (($uploaded_type == "image/jpeg") &amp;&amp; ($uploaded_size &lt; 100000)){

if(!move_uploaded_file($_FILES['uploaded']['tmp_name'], $target_path)) {

    echo '';
    echo 'Your image was not uploaded.';
    echo '';

} else {

    echo '';
    echo $target_path . ' succesfully uploaded!';
    echo '';

}
}
else{
    echo 'Your image was not uploaded.';
}
}
?>;

很多人都会用$uploaded_type == “image/jpeg”对图片类型进行验证,可是这样依然是不安全的。

<?php
if (isset($_POST['Upload'])) {
$target_path = DVWA_WEB_PAGE_TO_ROOT."hackable/uploads/";
$target_path = $target_path . basename($_FILES['uploaded']['name']);
$uploaded_name = $_FILES['uploaded']['name'];
$uploaded_ext = substr($uploaded_name, strrpos($uploaded_name, '.') + 1);
$uploaded_size = $_FILES['uploaded']['size'];

if (($uploaded_ext == "jpg" || $uploaded_ext == "JPG" || $uploaded_ext == "jpeg" || $uploaded_ext == "JPEG") &amp;&amp; ($uploaded_size &lt; 100000)){

if(!move_uploaded_file($_FILES['uploaded']['tmp_name'], $target_path)) {

    echo '';
    echo 'Your image was not uploaded.';
    echo '';

} else {

    echo '';
    echo $target_path . ' succesfully uploaded!';
    echo '';

}
}

else{

echo '';
echo 'Your image was not uploaded.';
echo '';
}
}

?>;

安全的图片验证类型可以这样写$uploaded_ext == “jpg” || $uploaded_ext == “JPG” || $uploaded_ext == “jpeg” || $uploaded_ext == “JPEG”),呵呵,也不难是吧,其实有些事情就这么简单,只是我们不知道而已。

JackSun

JackSun

I'm a coder.

You may also like...

2 Responses

  1. 路人 says:

    感觉判断扩展名依然不是很安全,如果我改个扩展名呢

  2. 王玲玉 says:

    好啊博主,没想到啊,太好了

Leave a Reply

Your email address will not be published.